我有一个域对象,为了这个问题的目的,我将使用以下私有变量调用Person:
String name
int age
每个人都有吸气剂和二传手.现在我还有一个Map< String,String>以下条目:
name, phil
age, 35
我想在Person类中填充所有setter方法的列表,然后循环遍历此列表并使用map中的值调用每个方法.
这是否可能,因为我在网上看不到任何接近这个的例子.非常感谢例子.
解决方法:
当然有可能!您可以通过执行以下操作获得以“set”开头的所有方法:
Class curClass = myclass.class;
Method[] allMethods = curClass.getMethods();
List setters = new ArrayList();
for(Method method : allMethods) {
if(method.getName().startsWith("set")) {
setters.add(method);
}
}
现在你已经掌握了这些方法.你是否已经知道如何为你的班级实例打电话?
标签:java,reflection,invoke
来源: https://codeday.me/bug/20190713/1450894.html