我问这个问题是因为我很好奇。我不想真正遍历一个类的派生类。我知道我在这里介绍的方法很草率这只是一个测试。
假设我有一个类(抽象的或非抽象的):
public class SomeClass {
// snip....
}
我可以很容易地编写一个方法来遍历类层次结构并找到一个 Field
例如:
private Field extractField(Class<?> type, String fieldName) {
Field ret = null;
try {
ret = type.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
Class<?> superclass = type.getSuperclass();
if (superclass == null) {
throw new IllegalArgumentException("Missing field detected.", e);
} else {
ret = extractField(superclass, fieldName);
}
}
return ret;
}
如果我想在 type
的派生类中搜索 Field
该怎么办?我在 java 反射包中没有发现任何有用的东西。
最佳答案
遍历派生类没有简单的方法,因为您不知道哪些类是从基类派生的。您可以使用 Reflections库来查找派生类。这通过检查类路径中类的字节码来工作,可以选择限制为包或预索引。
Now what can I do If I wish to search for a Field in the derived classes of type?
找到派生类后,您可以用相同的方式检查它们。
关于java - java中如何在类的派生类中查找字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13498477/