我问这个问题是因为我很好奇。我实际上不想遍历类的派生类。我知道我在这里介绍的方法很草率,这只是一个测试。
因此,假设我有一堂课(抽象与否):
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;
}
现在,如果我想在
Field
的派生类中搜索type
,该怎么办?我没有在Java反射包中找到任何有用的东西。 最佳答案
没有遍历派生类的简单方法,因为您不知道哪些类是从基类派生的。您可以使用Reflections库查找派生类。这可以通过检查类路径中类的字节码(可选地限于包或预索引)来工作。
现在,如果我想在派生类型中搜索字段,该怎么办?
一旦找到派生类,就可以用相同的方式检查它们。
关于java - 如何在Java中的类的派生类中找到字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13498477/