0

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.

Dims
  • 47,675
  • 117
  • 331
  • 600
  • I found [this answer](https://stackoverflow.com/a/5193884/7525132) here on SO. I do not feel like it answers this question perfectly, so I did not immediately flag a dupe, but it might help anyway. – Izruo Nov 26 '21 at 16:07
  • 1
    `getResources(…)` with a directory name only works when the underlying storage has directories, e.g. the default file system or in case of a jar file, when it has pseudo directory entries (which they usually don’t have). – Holger Nov 29 '21 at 09:54

2 Answers2

2

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.

Izruo
  • 2,246
  • 1
  • 11
  • 23
  • I took this code from Spring, for example: https://github.com/spring-projects/spring-framework/blob/main/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java#L339 – Dims Nov 26 '21 at 19:13
-1

Try with

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

while (urls.hasMoreElements()) {
    System.out.println(urls.nextElement());
}
adlmez
  • 42
  • 3