假设我有几种此类的课程:
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.....
}
我想遍历所有包含的子类(不继承),并获取嵌套对象树中所有fields的列表。但是,当我使用这样的反射代码时:
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访问嵌套字段?
谢谢。
假设我有几种这种风格的类:public class A {public B element; }公共类B {公共C anotherElement; // C代表另一个包含D类型的类型,...
可以在循环中尝试以下语句吗?
只是一点递归: