How to safely access the URLs of all resource files in the classpath in Java 9/10?

前端 未结 2 570
无人及你
无人及你 2020-12-24 11:21

We learned from the release notes of Java 9 that

The application class loader is no longer an instance of java.net.URLClassLoader (an implementation

相关标签:
2条回答
  • 2020-12-24 11:35

    AFAIK you can parse the java.class.path system property to get the urls:

    String classpath = System.getProperty("java.class.path");
    String[] entries = classpath.split(File.pathSeparator);
    URL[] result = new URL[entries.length];
    for(int i = 0; i < entries.length; i++) {
        result[i] = Paths.get(entries[i]).toAbsolutePath().toUri().toURL();
    }
    
    System.out.println(Arrays.toString(result)); // e.g. [file:/J:/WS/Oxygen-Stable/jdk10/bin/]
    
    0 讨论(0)
  • 2020-12-24 11:41

    I think this is an XY problem. Accessing the URLs of all resources on the classpath is not a supported operation in Java and is not a good thing to try to do. As you have already seen in this question, you will be fighting against the framework all the way if you try to do this. There will be a million edge cases that will break your solution (custom classloaders, EE containers, etc. etc.).

    Please could you expand on why you want to do this?

    If you have some kind of plugin system and are looking for modules that interface with your code which may have been provided at runtime, then you should use the ServiceLoader API, i.e.:

    A service provider that is packaged as a JAR file for the class path is identified by placing a provider-configuration file in the resource directory META-INF/services. The name of the provider-configuration file is the fully qualified binary name of the service. The provider-configuration file contains a list of fully qualified binary names of service providers, one per line. For example, suppose the service provider com.example.impl.StandardCodecs is packaged in a JAR file for the class path. The JAR file will contain a provider-configuration file named:

    META-INF/services/com.example.CodecFactory
    

    that contains the line:

    com.example.impl.StandardCodecs # Standard codecs
    
    0 讨论(0)
提交回复
热议问题