arash arash - 2 months ago 4
Java Question

Get all of the Classes in the Classpath

How can I get list of all available classes in

at runtime?

In Eclipse IDE, you can do this by pressing Ctrl+Shift+T.

Is there any method in Java to get it done?


You can get all classpath roots by passing an empty String into ClassLoader#getResources().

Enumeration<URL> roots = classLoader.getResources("");

You can construct a File based on URL as follows:

File root = new File(url.getPath());

You can use File#listFiles() to get a list of all files in the given directory:

for (File file : root.listFiles()) {
    // ...

You can use the standard methods to check if it's a directory and/or to grab the filename.

if (file.isDirectory()) {
    // Loop through its listFiles() recursively.
} else {
    String name = file.getName();
    // Check if it's a .class file or a .jar file and handle accordingly.

Depending on the sole functional requirement, I guess that the Reflections library is much more exactly what you want.