I’m looking for some clarification on how getClasses() works. I am trying to write code that, given a String classname, finds all classes that extend the class specified by classname. I have a method called getChildren() which does this. Unfortunately, every time I call it, the method returns an empty Collection. Here is my code.
import java.util.ArrayList;
import java.util.Collection;
public class ClassFinder {
private Class<?> myClass;
public ClassFinder(Class<?> clazz) {
myClass = clazz;
}
public ClassFinder (String className) throws ClassNotFoundException {
myClass = Class.forName(className);
}
public Collection<Class<?>> getChildren() {
Collection<Class<?>> children = new ArrayList<Class<?>>();
Class<?>[] relatedClasses = myClass.getClasses();
for (Class<?> potentialChild : relatedClasses) {
if (potentialChild.isAssignableFrom(myClass)) {
children.add(potentialChild);
}
}
return children;
}
}
getClasses returns the classes enclosed in the current class. You want to find the classes that inherit from the current class. Unfortunately there are no methods in the Java API that let you do this.
You can look through the loaded classes however: How can I list all classes loaded in a specific class loader