Reputation: 701
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;
}
}
Upvotes: 0
Views: 5732
Reputation: 42005
What you can do is create your own classloader and use that to load the classes, in that class loader you can keep the list of all the classes you have loaded.
Then whenever you need to find how many classes extend a given class, you can go through all the classes in the list and use this method of Class getSuperclass()
to find out whether the value returned by this method is same as the class you are trying to find children of.
But there is a limitation of this code that it may not return all the classes that you expect. That is because all the classes that extend a given class may not have loaded when you execute the code.
Upvotes: 0
Reputation: 28753
If you read the documentation for getClasses()
...
Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.
Keywords: "that are members" - not classes that extend this class. This method will give you the inner classes, not the child classes.
Run this example:
public class Example {
public static void main(String[] argv) {
for(Class c:Example.class.getClasses()) {
System.out.println(c.getName());
}
}
public class InnerClass {
}
}
And you'll get this output:
Example$InnerClass
Upvotes: 0
Reputation: 30042
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
Upvotes: 5