Method类的Invoke方法

Dto:dto里面放的都是同一类型的字段

/*
 * Creation : 2 Dec 2015
 */
package com.java.invoke;

public class Dto {

    private Integer Col1;
    private Integer Col2;
    private Integer Col3;
    private Integer Col4;

    public Integer getCol1() {
        return Col1;
    }

    public void setCol1(Integer col1) {
        Col1 = col1;
    }

    public Integer getCol2() {
        return Col2;
    }

    public void setCol2(Integer col2) {
        Col2 = col2;
    }

    public Integer getCol3() {
        return Col3;
    }

    public void setCol3(Integer col3) {
        Col3 = col3;
    }

    public Integer getCol4() {
        return Col4;
    }

    public void setCol4(Integer col4) {
        Col4 = col4;
    }

}

下面要把list里面的数据逐一放入dto中

/*
 * Creation : 2 Dec 2015
 */
package com.java.invoke;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class TestInvoke {

    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(new Integer[] { 3, 5, 8 });

        Class<?> clazz = Class.forName(Dto.class.getName());

        int index = 1;

        Dto dto = new Dto();

        for (Integer value : list) {

            Method method = clazz.getDeclaredMethod("setCol" + index, Integer.class);

            method.invoke(dto, value);

            index++;

        }
        

    }
}


你可能感兴趣的:(java,invoke)