使用 Java 反射检索继承的属性名称/值
我有一个从 'ParentObj' 扩展而来的 Java 对象 'ChildObj'.现在,是否可以使用 Java 反射机制检索 ChildObj 的所有属性名称和值,包括继承的属性?
I've a Java object 'ChildObj' which is extended from 'ParentObj'. Now, if it is possible to retrieve all the attribute names and values of ChildObj, including the inherited attributes too, using Java reflection mechanism?
Class.getFields 给我公共属性数组,Class.getDeclaredFields 给了我所有字段的数组,但没有一个包含继承的字段列表.
Class.getFields gives me the array of public attributes, and Class.getDeclaredFields gives me the array of all fields, but none of them includes the inherited fields list.
有什么办法也可以检索继承的属性吗?
Is there any way to retrieve the inherited attributes also?
不,你需要自己写.这是一个简单的递归方法,调用 Class.getSuperClass():
no, you need to write it yourself. It is a simple recursive method called on Class.getSuperClass():
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null) {
getAllFields(fields, type.getSuperclass());
}
return fields;
}
@Test
public void getLinkedListFields() {
System.out.println(getAllFields(new LinkedList<Field>(), LinkedList.class));
}