【发布时间】:2020-01-06 15:27:31
【问题描述】:
假设我有几个这种风格的类:
public class A {
public B element;
}
public class B {
public C anotherElement; // where C refers to another type which contains types D, E, F, etc.....
}
我想遍历所有包含的子类(不继承)并获取嵌套对象树中所有字段的列表。但是,当我使用这样的反射代码时:
Field[] myFields = providedObject.getClass().getDeclaredFields();
for (Field myField : myFields) {
// do something here?? to access the sub-fields of the class
// if I print out myField.getName(), I get the element of class A, but I also want to access the anotherElement of class B (without hard-coding the name 'anotherElement', I want a full traversal of all nested fields)
}
在“在此处执行操作”步骤中,我想访问 myField 的子字段,但我在 Field api 中看不到任何可以直接让我执行此操作的内容。我试过了:
myField.getDeclaringClass().getDeclaredFields() -> 这似乎返回了我们已经看到的相同元素,而不是子元素
和
myField.getClass().getDeclaredFields() -> 这似乎返回“Field”类的字段,而不是我的 A 或 B 类
那么我将如何从反射 api 访问嵌套字段?
谢谢。
【问题讨论】:
标签: java reflection field