I need to enumerate all classes in a package and add them to a List. The non-dynamic version for a single class goes like this:
List allClasses = new ArrayList();
allClasses.add(String.class);
How can I do this dynamically to add all classes in a package and all its subpackages?
Update: Having read the early answers, it’s absolutely true that I’m trying to solve another secondary problem, so let me state it. And I know this is possible since other tools do it. See new question here.
Update: Reading this again, I can see how it’s being misread. I’m looking to enumerate all of MY PROJECT’S classes from the file system after compilation.
****UPDATE 1 (2012)****
OK, I’ve finally gotten around to cleaning up the code snippet below. I stuck it into it’s own github project and even added tests.
https://github.com/ddopson/java-class-enumerator
****UPDATE 2 (2016)****
For an even more robust and feature-rich classpath scanner, see https://github.com/classgraph/classgraph . I’d recommend first reading my code snippet to gain a high level understanding, then using lukehutch’s tool for production purposes.
****Original Post (2010)****
Strictly speaking, it isn’t possible to list the classes in a package. This is because a package is really nothing more than a namespace (eg com.epicapplications.foo.bar), and any jar-file in the classpath could potentially add classes into a package. Even worse, the classloader will load classes on demand, and part of the classpath might be on the other side of a network connection.
It is possible to solve a more restrictive problem. eg, all classes in a JAR file, or all classes that a JAR file defines within a particular package. This is the more common scenario anyways.
Unfortunately, there isn’t any framework code to make this task easy. You have to scan the filesystem in a manner similar to how the ClassLoader would look for class definitions.
There are a lot of samples on the web for class files in plain-old-directories. Most of us these days work with JAR files.
To get things working with JAR files, try this…