java - 使用反射为setter方法赋值
问题描述
如何在运行时创建对象并设置对象中所有设置器值的值?我在运行时使用 jsonschema2pojo.Classes 字段可以更改以下类,
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
推荐阅读
- pyarrow - 如何使用 ExtensionType 制作 pyarrow.DictionaryArray?使用 from_buffers?使用演员表?
- amazon-web-services - 使用 dms 将 kinesis 连接为目标时出错
- python - 如何将稀疏向量作为列添加到 Pyspark Dataframe
- sqlalchemy - SQLAlchemy - 在对象中执行搜索词结果
- sql-server - 无法在 Azure SQL 跨数据库查询中按日期时间类型进行筛选
- php - 如何在购物车页面上添加 Woocommerce 产品属性术语作为正文类
- python - Numpy:从一维整数数组创建新数组,其中整数数组中的每个元素代表新数组中元素的数量
- r - 在R中将数据更改为不同的格式
- html - Div 按钮悬停:过渡线性渐变
- java - 如何引用属性为“CS1310”或“MATH 1510”的元组?我试过 getChar 但不工作