Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

Tags:

java

resources

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

like image 214
vitaut Avatar asked Jun 09 '11 19:06

vitaut


People also ask

What is the difference between class getResource () and ClassLoader getResource ()?

Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.

When would you use a ClassLoader?

Java uses ClassLoader implicitly when you use new , import keyword, the jvm will use the current class's classloader to load the dependent classes, so you can use the custom classloader to load a bootstrap class explicitly by using classloader.

How do I know what ClassLoader loads a class?

To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException.

What is ClassLoader getResource?

getResource() method finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.


1 Answers

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()

like image 121
Sripathi Krishnan Avatar answered Sep 20 '22 10:09

Sripathi Krishnan