How to list all resources without specifying a package name or file system path for jar files in Java 9

in java 7 and 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 is 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 the resources without knowing the package prefix or the file system path to the jar files?

+4
source share
3 answers

The best answer I've found is to provide the getResources argument, of course, that means you know the prefix of the path where 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()));
     }
  }
0
source

The Java9 release notice reads:

java.net.URLClassLoader ( , ). , , ClassLoader.getSytemClassLoader() URLClassLoader . , Java SE JDK API .

, , :

readable Jigsaw.

+2

- :

URLClassLoader, , , . , Java SE, JDK .

https://docs.oracle.com/javase/9/migrate/toc.htm

classpath - ModuleFinder .

0

Source: https://habr.com/ru/post/1689221/


All Articles