在 Java 7 和 8 中,我曾经能够做到
URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
System.out.println("*************** url=" + url);
}
但是在 Java 9 中,上面给出了一个错误
java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader
那么如何在不知道 jar 文件的包前缀或文件系统路径的情况下列出所有资源呢?
最佳答案
The application class loader is no longer an instance of
java.net.URLClassLoader
(an implementation detail that was never specified in previous releases). Code that assumes thatClassLoader.getSytemClassLoader()
returns aURLClassLoader
object will need to be updated. Note that Java SE and the JDK do not provide an API for applications or libraries to dynamically augment the class path at run-time.
至add to this from the mailing list很少有资源查找方法包括以下方法:
Class::getResourceAsStream
读取它自己的资源。方法,返回 InputStream
.它可以通过 Class::getResource
获取到它自己的资源之一的 URL。方法。这些方法不会在其他命名模块中定位资源。 ClassLoader::getResource*
方法不会在任何位置定位资源命名模块。
Class
中的所有现有资源查找方法和 ClassLoader
像今天一样为类路径上的资源工作。 Module::getResourceAsStream
方法可以用于读取任何命名模块的资源,没有限制。
这些选择提供了resource encapsulation 两者之间的平衡。和 readable artifact对拼图的要求。
关于java - 如何在不知道 Java 9 中 jar 文件的包名或文件系统路径的情况下列出所有资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47275985/