Can you tell me what is the difference between Thread.currentThread().getContextClassLoader()
and TestServlet.class.getClassLoader()
do not mark it as duplicate and also please explain as well as provide me example when to use these
Java File:
package com.jar.test;
public class TestServlet {
public static void main(String args[]) {
ClassLoader cls = TestServlet.class.getClassLoader().loadClass(
"com.jar.test.TestServlet");
ClassLoader cls = Thread.currentThread().getContextClassLoader()
.loadClass("com.jar.test.TestServlet");
}
}
Thread.currentThread().getContextClassLoader()Returns the context ClassLoader for this Thread . The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources.
As we can see, there are three different class loaders here: application, extension, and bootstrap (displayed as null). The application class loader loads the class where the example method is contained. An application or system class loader loads our own files in the classpath.
Custom class loaders You might want to write your own class loader so that you can load classes from an alternate repository, partition user code, or unload classes.
Java ClassLoader is used to load the classes at run time. In other words, JVM performs the linking process at runtime. Classes are loaded into the JVM according to need. If a loaded class depends on another class, that class is loaded as well.
Thread.currentThread().getContextClassLoader()
Returns the context
ClassLoader
for thisThread
. The contextClassLoader
is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is theClassLoader
context of the parent Thread. The contextClassLoader
of the primordial thread is typically set to the class loader used to load the application.
Class#getClassLoader()
Returns the class loader for the class. Some implementations may use
null
to represent the bootstrap class loader. This method will returnnull
in such implementations if this class was loaded by the bootstrap class loader.
In a nutshell:
Thread.currentThread().getContextClassLoader()
is the ClassLoader
of the context of the thread that has been set with setContextClassLoader(ClassLoader cl)
. Imagine that you have a complex java application with a hierarchy of ClassLoader
(for example an Application Server) and you want your current thread to load classes or resources from one specific ClassLoader
in this hierarchy, you can do it by simply setting the context ClassLoader
of the thread to this specific ClassLoader
.
Class#getClassLoader()
is simply the ClassLoader
from which your instance of Class
has been loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With