41

I saw both Class.getResource and ClassLoader.getSystemResource used to locate a resource in Java. Is there any reason to prefer one to another?

vitaut
  • 49,672
  • 25
  • 199
  • 336

4 Answers4

50

There are several ways to load resources, each with a slightly different meaning -

ClassLoader::getSystemResource() uses the system classloader. This uses the classpath that was used to start the program. If you are in a web container such as tomcat, this will NOT pick up resources from your WAR file.

Class<T>#getResource() prepends the package name of the class to the resource name, and then delegates to its classloader. If your resources are stored in a package hierarchy that mirrors your classes, use this method.

ClassLoader#getResource() delegates to its parent classloader. This will eventually search for the resource all the way upto the system classloader.

If you are confused, just stick to ClassLoader#getResource()

jordanpg
  • 6,386
  • 4
  • 46
  • 70
Sripathi Krishnan
  • 30,948
  • 4
  • 76
  • 83
4

From Class.getResource( )

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

and ClassLoader.getSystemResource( )

Find a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
0

Using Methods of java.lang.Class:

public java.net.URL getResource(String name) {
  name = resolveName(name);
  ClassLoader cl = getClassLoader();
  if (cl==null) {
    return ClassLoader.getSystemResource(name);  // A system class.
  }
  return cl.getResource(name);
}
01pshe
  • 1
  • 1
0

ClassLoader.getSystemResource() will use the bootstrap (system) classloader.

Class.getResource() will use that particular instance of Class's classloader, in other words whatever classloader was used to load that class. This may be a different classloader than the system classloader.

David
  • 1,481
  • 11
  • 19