Home > Software engineering >  Can't enumerate `class` files with ClassLoader#getResources()
Can't enumerate `class` files with ClassLoader#getResources()

Time:11-27

I am trying to enumerate classes in the package with

Enumeration<URL> resourceUrls = myObject.getClassLoader().getResources("path/to/my/package/");
while (resourceUrls.hasMoreElements()) {
   ...

Unfortunately it returns nothing. Why?

Assuming path is correct. Path starts with no slash and ends with slash. There are several public classes under path.to.my.package package.


I took this code from Spring.

CodePudding user response:

You cannot walk a class path like you can walk a file path. Walking a file path is done on the file system, which does not apply to a class path.

While a java class path entries are formed like file paths and usually are folders and files (either on the file system or inside a JAR archive), it does not necessarily have to be that way. In fact, the classes of one single package may originate from various locations of differing nature: one might be loaded from a local JAR file while another one might be loaded from a remote URL.

The method ClassLoader.getResources() exists to provide access to all "occurrences" of a resource if it has the same name in different JAR files (or other locations). For example you can use

ClassLoader.getSystemClassLoader().getResources("META-INF/MANIFEST.MF");

to access the manifest file of each JAR file in your class path.

CodePudding user response:

Try with

Enumeration<URL> urls = ClassLoader.getSystemClassLoader().getResources("path/to/my/package");

while (urls.hasMoreElements()) {
    System.out.println(urls.nextElement());
}
  • Related