我认为这应该为您指明正确的方向:
import java.beans.*for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) { if (pd.getReadMethod() != null && !"class".equals(pd.getName())) System.out.println(pd.getReadMethod().invoke(foo));}请注意,您可以自己创建BeanInfo或PropertyDescriptor实例,即无需使用Introspector。但是,Introspector在内部进行一些缓存,这通常是一件好事(tm)。如果没有缓存就很开心,甚至可以去
// TODO check for non-existing readMethodObject value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);但是,有很多库可以扩展和简化java.beans API。Commons BeanUtils是一个众所周知的示例。在那里,您只需执行以下操作:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils附带了其他方便的东西。即即时值转换(对象到字符串,字符串到对象)以简化用户输入的设置属性。



