首页 > 解决方案 > 使用反射为setter方法赋值

问题描述

如何在运行时创建对象并设置对象中所有设置器值的值?我在运行时使用 jsonschema2pojo.Classes 字段可以更改以下类,

class Foo
(

int a ;
int b;

List <Abc> list;
//getters and setter ommited
}

class Abc
{

int c ;
int d;

}

标签: javaspring-bootreflection

解决方案


这是我们如何通过反射实现这一点的想法:

class Foo {
    int a;
    int b;
    List<Abc> list;
}

class Abc {
    int c;
    int d;
}


public class FillSettersThroughReflection {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Method[] publicMethods = Foo.class.getMethods(); //get all public methods
        final Foo foo = Foo.class.getDeclaredConstructor().newInstance(); //will only work when you will have default constructor
        //using java 8
        Stream.of(publicMethods).filter(method -> method.getName().startsWith("set"))
                .forEach(method -> {
                    //you can write your code
                });

        //in java older way
        for (Method aMethod : publicMethods) {
            if (aMethod.getName().startsWith("set")) {
                aMethod.invoke(foo, <your value>); //call setter-method here
            }
        }
    }
}

您可以将条件放在过滤器之后,然后在传递值set之后调用方法。invoke


推荐阅读