Reflector:如何列出类的getter并在Java中调用它们?
下面的文章很好地展示了如何使用内省来列出与类关联的getter 我在这篇文章中使用的代码是:Reflector:如何列出类的getter并在Java中调用它们?,java,reflection,Java,Reflection,下面的文章很好地展示了如何使用内省来列出与类关联的getter 我在这篇文章中使用的代码是: for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){ System.out.println(propertyDescriptor.getReadMethod()); } 这适用于我的“
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(User.class,Object.class).getPropertyDescriptors()){
System.out.println(propertyDescriptor.getReadMethod());
}
这适用于我的“用户”类,输出为:
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.invoke(对象实例、对象…参数)
类似于
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
}
}
太好了,非常感谢你。您只需要添加一个右括号来关闭try语句。@SingleEntity不客气!感谢您现在指出排版问题:)