1. 程式人生 > 實用技巧 >陣列的值賦給實體類的屬性

陣列的值賦給實體類的屬性

為實體類擴充套件欄位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); } }