下面的 SO 文章很好地展示了如何使用内省(introspection)器列出与类关联的 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());
}
这对于我的“User”类效果很好,输出为:
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()
我现在的问题是,我现在如何调用这些方法?如果在链接中以某种方式解释了这一点,我深表歉意,但我不明白它,并且非常感谢一个例子。
当然,我知道如何正常调用类方法,但这里的假设是,在上面的代码发现 getter 之前,程序不知道它们。
最佳答案
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
}
}
关于java - 反射器: How to list getters of a class and invoke them in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26911944/