Search code examples
javaclassloader

How can I enumerate all child classes of a superclass in Java


My application consists of several JAR files. I would like to iterate over all of the JAR files and find all classes that subclass a particular class, so that I can cause their static initializers to run.

I looked though the Javadocs for java.lang.ClassLoader, but can't find any method that does this.

I am trying to implement the "Product Trader" pattern (http://www.ubilab.com/publications/print_versions/pdf/plop-96-producttrader.pdf), with the classes "self-registering" in the abstract superclass. The superclass will have a HashMap that maps the service a subclass provides and the java.lang.Class file that handles that service.

The problem is that a class does not run it's static initializers until it is loaded. If I can iterate all of the subclasses, I can force each to load and run it's initializers.

Thanks, Ralph


Solution

  • This is not generally solvable. A ClassLoader is not required to be able to iterate over the Classes it could load. The easiest example of a ClassLoader that can't do that is when you load classes from a http:// base URL: HTTP provides no standardized way to enumerate the content of any given URL.

    An better way to implement this is to use the ServiceLoader and let all implementing classes register themselves via a simple entry in their jar file.