Difference Between Getclass().Getclassloader().Getresource() and Getclass.Getresource()

Difference between getClass().getClassLoader().getResource() and getClass.getResource()?

The second one calls the first one. The difference is described in the javadoc.

The first one takes paths that don't start with a /, and always starts at the root of the classpath.

The second one takes path that can start with a /. If it does, it starts at the root of the classpath. If not, it starts at the package of the class on which the method is called.

So getClass().getClassLoader().getResource("foo/bar.txt") is equivalent to getClass().getResource("/foo/bar.txt").

And, assuming getClass() returns a class that is in the package foo, getClass().getResource("bar.txt") is equivalent to getClass().getClassLoader().getResource("foo/bar.txt")

What is the difference between Class.getResource() and ClassLoader.getResource()?

To answer the question whether there is any caching going on.

I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.

However:
I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.

I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.

this.getClass().getClassLoader().getResource(...) and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package.
If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar

I thought this question was already asked and answered!

  • What is the difference between Class.getResource() and
    ClassLoader.getResource()?

getClass().getResource() searches relative to the .class file while
getClass().getClassLoader().getResource() searches relative to the
classpath root.

If there's an SSCCE here, I don't understand why it doesn't

1) Show the directory organization in the .jar, and...

2) Take package into consideration

Q: What (if anything) hasn't already been answered by What is the difference between Class.getResource() and ClassLoader.getResource()? (and the links it cites)?

=========================================================================

I'm still not sure what isn't clear, but this example might help:

/*
SAMPLE OUTPUT:
ClassLoader.getResource(/subdir/readme.txt): NULL
Class.getResource(/subdir/readme.txt): SUCCESS

ClassLoader.getResource(subdir/readme.txt): SUCCESS
Class.getResource(subdir/readme.txt): NULL
*/
package com.so.resourcetest;

import java.net.URL;

public class ResourceTest {

public static void main(String[] args) {
ResourceTest app = new ResourceTest ();
}

public ResourceTest () {
doClassLoaderGetResource ("/subdir/readme.txt");
doClassGetResource ("/subdir/readme.txt");
doClassLoaderGetResource ("subdir/readme.txt");
doClassGetResource ("subdir/readme.txt");
}

private void doClassLoaderGetResource (String sPath) {
URL url = getClass().getClassLoader().getResource(sPath);
if (url == null)
System.out.println("ClassLoader.getResource(" + sPath + "): NULL");
else
System.out.println("ClassLoader.getResource(" + sPath + "): SUCCESS");
}

private void doClassGetResource (String sPath) {
URL url = getClass().getResource(sPath);
if (url == null)
System.out.println("Class.getResource(" + sPath + "): NULL");
else
System.out.println("Class.getResource(" + sPath + "): SUCCESS");
}
}

Here's the corresponding directory tree. It happens to be an Eclipse project, but the directories are the same regardless if it's Eclipse, Netbeans ... or a .jar file:

C:.
├───.settings
├───bin
│ ├───com
│ │ └───so
│ │ └───resourcetest
│ └───subdir
└───src
├───com
│ └───so
│ └───resourcetest
└───subdir

The file being opened is "subdir/readme.txt"


ADDENDUM 11/9/12:

Hi -

I copied your code verbatim from github, re-compiled and re-ran:

ClassLoader.getResource(/subdir/readme.txt): NULL
Class.getResource(/subdir/readme.txt): SUCCESS
ClassLoader.getResource(subdir/readme.txt): SUCCESS
Class.getResource(subdir/readme.txt): NULL

If that's not the output you're getting ... I'm baffled.

For whatever it's worth, I'm running:

  • Eclipse Indigo (it shouldn't matter)

  • Running inside the IDE (it shouldn't matter if it's filesystem or .jar, inside or outside an IDE)

  • My JRE is 1.6 (if anything, this is probably the biggie)

Sorry we haven't been able to resolve what I thought was a straightforward issue :(


ADDENDUM 11/21/12 (Andreas):

Since there was no recent activity on this question, I would like to summarize what we found:

  • From our common understanding, the answer to the above question is: "No, it is not possible that Class.getResource("/path/image.png") returns a valid URL, while ClassLoader.getResource("path/image.png") returns null":

    • We're completely clear on the difference between ClassLoader.getResource() and Class.getResource()
    • Our sample outputs match, for both "SUCCESS" and for "null"
    • The sample outputs match what we'd expect
    • Conclusion: Either we oversaw something, or something different caused the "solution" described in the linked question to work. I think we can not currently prove one or the other.

What is the difference between getResourceAsStream with and without getClassLoader?

From the Javadoc for Class.getResourceAsStream():

This method delegates to this object's class loader.
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form:
    modified_package_name/name
    Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

In other words, they do the same thing if the "path" begins with a "/", but if not, then in the latter case, the path will be relative to the class's package, whereas the classloader one will be absolute.

In short, the first fetches path/to/my/properties and the second fetches package/of/myclass/path/to/my/properties.



Related Topics



Leave a reply



Submit