我认为这应该指向正确的方向:
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在内部执行一些缓存,这通常是一个Good Thing(tm)。如果你快乐没有缓存,你甚至可以去
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
但是,有很多库来扩展和简化java.beans API。 Commons BeanUtils是一个众所周知的例子。在那里,你只要做:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils自带了其他方便的东西。即即时值转换(对象到字符串,字符串到对象),以简化来自用户输入的属性设置。