Search code examples
javaurlclasspathclassloadergetresource

getResource("/some.jar") returns null, although "some.jar" exists in getURLs()


After hours I am giving up on debugging the following:

This works:

URL[] urls = ((URLClassLoader) MyClass.class.getClassLoader()).getURLs();
    URL myURL = null;
    for (URL url : urls) {
        if (url.getPath().endsWith("some.jar")) {
            myURL = url;
    }   
}
System.out.println(myURL);

returns

file:/C:/Users/Me/.m2/repository/path/to/some.jar

However, all of the following returns null:

MyClass.class.getClassLoader()).getResource("/some.jar");
MyClass.class.getClassLoader()).getResource("some.jar");
MyClass.class.getClassLoader()).getResource("/C:/Users/Me/.m2/repository/path/to/some.jar");
MyClass.class.getClassLoader()).getResource("/path/to/some.jar");

As you can see, I would like to get a jar of the user's maven repository by not adressing it absolutely, if possible. The jar is in the classpath, as shown by getURLs()
But how the heck do I have to address it in getResource() in order to get it?

Any help is appreciated!


Solution

  • URLClassLoader.getURLs() returns the URLs to directories and JARs that are in the classpath. ClassLoader.getResource(String) is looking for the resource inside the classpath. So unless one of your JARs/directories in the classpath contains some.jar, this is expected to fail.

    Put another way, if some.jar contains pkg/thingy.png, then getResource("pkg/thingy.png") would succeed.

    Also note that getResource(String) returns a URL to the resource... a URL that you already have in myURL.