Daniel K
Daniel K

Reputation: 3067

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!

Upvotes: 1

Views: 3215

Answers (2)

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500575

I suspect you want:

MyClass.class.getClassLoader().getResource("path/to/some.jar")

Note the lack of leading slash. That's assuming the "root" of your classloader is effectively repository. It's hard to tell just from the URL.

An alternative would be to use:

MyClass.class.getResource("/path/to/some.jar")

Note that this time there is a leading slash. Basically classloaders don't have any concept of a "relative" name, whereas classes do.

Upvotes: 0

Related Questions