I ask this question because I’m curious. I don’t want to actually traverse the derived classes of a class. I know that the method I present here is sloppy this is just a test.
So suppose I have a class (abstract or not):
public class SomeClass {
// snip....
}
I can easily write a method to walk up the class hierarchy and find a Field for example:
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;
}
Now what can I do If I wish to search for a Field in the derived classes of type? I did not find anything useful in the java reflection packages.
There is no simple way to traverse derived classes as you don’t know which classes are derived from a base class. You can use the Reflections library to find derived classes. This works by examining the byte code of the classes in your class path, optionally limited to package(s) or pre-indexed.
Once you have found the derived classes you can examine these in the same way.