Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

What is the difference between getClass().getClassLoader().getResource() and getClass.getResource()?

When retrieving files from resources, which one should I use in what circumstances?

like image 858
Jimmy C Avatar asked Feb 06 '13 21:02

Jimmy C


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.

What does getClassLoader do?

getClassLoader() method returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. The method will return null in such implementations if this class was loaded by the bootstrap class loader.

What is getClassLoader () getResourceAsStream?

getClassLoader(). getResourceAsStream("abc. txt") and find that it searchs the resource in all jar file and zip file in class path. Thats correct when you work only with a single ClassLoader (most non-OSGi/ non-modular environments).

What is ClassLoader in Java with example?

The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application.


2 Answers

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

like image 161
JB Nizet Avatar answered Sep 30 '22 15:09

JB Nizet


which one should I use in what circumstances?

Neither. You should call Thread.currentThread().getContextClassLoader().

This has the benefit of not needing to be changed depending on whether you're calling from a static or instance method.

And more important, it will properly handle classloader delegation inside a container. If you don't use it, you might find that an "application" resource isn't found because the class that's loading it was loaded by a classloader higher up the delegation hierarchy.

like image 34
parsifal Avatar answered Sep 30 '22 17:09

parsifal