以下SO文章非常清楚地展示了如何使用introspector列出与类关联的getter。
Java Reflection: How can i get the all getter methods of a java class and invoke them
我在这篇文章中使用的代码是:
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
System.out.println(propertyDescriptor.getReadMethod());
}
这适用于我的用户' class,输出为:
public java.lang.String com.SingleEntity.mind_map.User.getName()
public int com.SingleEntity.mind_map.User.getNumber_of_entries()
public java.lang.String com.SingleEntity.mind_map.User.getUser_created_date()
我现在的问题是,我现在如何调用这些方法?如果在链接的SO中以某种方式解释了这一点我道歉但我不理解它并且真的很感激一个例子。
当然我知道如何正常调用Class方法,但这里的假设是程序不知道getter,直到上面的代码发现它们。
答案 0 :(得分:1)
PropertyDescriptor.getReadMethod()
会返回Method
个对象。
只需使用Method.invoke(Object instance, Object... args)
即可。
......中的某些内容......
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
try {
Object value = propertyDescriptor
.getReadMethod()
.invoke(myUserInstance, (Object[])null);
}
catch (IllegalAccessException iae) {
// TODO
}
catch (IllegalArgumentException iaee) {
// TODO
}
catch (InvocationTargetException ite) {
// TODO
}
}