使用反射为资源库方法赋值



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

class Foo
(
int a ;
int b;
List <Abc> list;
//getters and setter ommited
}
class Abc
{
int c ;
int d;
}

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

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方法。

最新更新