数组的值赋给实体类的属性

为实体类扩展字段col 赋值,扩展字段不确定多少,传入数组元素不确定,这时我们用到了反射的方法,遍历进行赋值。

package com.dream.bean;

import java.lang.reflect.Method;

public class Student {
    //固定字段
    private  String  name;

    //  扩展字段,未知
    private  Object  col1;
    private  Object  col2;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getCol1() {
        return col1;
    }

    public void setCol1(Object col1) {
        this.col1 = col1;
    }

    public Object getCol2() {
        return col2;
    }

    public void setCol2(Object col2) {
        this.col2 = col2;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", col1=" + col1 +
                ", col2=" + col2 +
                '}';
    }

    private    void   init(Object[]  arrs) throws Exception {
        Class<? extends Student> stuClass = this.getClass();
        for(int i=0;i<arrs.length;i++){
            String  methodName="setCol"+(i+1);
            Method method = stuClass.getDeclaredMethod(methodName, Object.class);
            method.setAccessible(true);
            method.invoke(this,arrs[i]);
        }
    }
    public  Student(String name,Object[] arrs) throws Exception {
        this.name=name;
        init(arrs);
    }
}

             
             

 

posted @ 2020-08-27 15:50  春眠不觉笑  阅读(1163)  评论(0编辑  收藏  举报