gpt4 book ai didi

java - 如何在不知道 Java 9 中 jar 文件的包名或文件系统路径的情况下列出所有资源

转载 作者:行者123 更新时间:2023-12-01 04:45:07 27 4
gpt4 key购买 nike

在 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 文件的包前缀或文件系统路径的情况下列出所有资源呢?

最佳答案

Java9 Release Note指出:

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 that ClassLoader.getSytemClassLoader() returns a URLClassLoader 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/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com