Search code examples
javaresourcesclassloaderjava-9

How to list all resources without know the package name or filesystem path for jar files in Java 9


in Java 7 & 8 I use to be able to do

URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
    System.out.println("*************** url=" + url);
}

But in Java 9 the above gives an error

java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader

So how do I list all resources without knowing the package prefix or the filesystem path of the jar files?


Solution

  • Best answer I found is to provide an argument to getResources, of course means you know prefix of the path the resources are located

      ArrayList<URL> resources = new ArrayList<URL>();
      ClassLoader urlLoader = ClassLoader.getSystemClassLoader();
      Enumeration<URL> eU = urlLoader.getResources("com");
      while (eU.hasMoreElements()) {
         URL u = eU.nextElement();
         JarFile jarFile = new JarFile(u.getFile().replace("file:/", "").replaceAll("!.*$", ""));
         Enumeration<JarEntry> e = jarFile.entries();
         while (e.hasMoreElements()) {
            JarEntry jarEntry = e.nextElement();
            resources.add(urlLoader.getResource(jarEntry.getName()));
         }
      }