What is the difference between the different ClassLoaders in Java and when to use what?
A class loader is an object that is responsible for loading classes or resources. In general, when loading a resource dynamically, you can choose from at least three classloaders:
The system classloader:
This is also referred to as the application classholder and handles –classpath.
ClassLoader c1 = ClassLoader.getSystemClassLoader();
The current classloader:
The current classloader loads and defines the class to which your current method belongs. Class.getClassLoader() returns the ClassLoader that loaded the class it is invoked on.
ClassLoader c2 = getClass().getClassLoader();
The current thread context classloader:
ClassLoader c3 = Thread.currentThread().getContextClassLoader();
Thread.getContextClassLoader() returns the ClassLoader set as the context ClassLoader for the Thread it is invoked on. This can be different from the ClassLoader that loaded the Thread class itself if the Thread's setContextClassLoader(ClassLoader) method has been invoked. This can be used to allow the object starting a thread to specify a
ClassLoader, the objects running in that thread should use. The cooperation of some of those objects is required for it to work.
Example:
Properties files are an example of a resource that is loaded using ClassLoaders. Both current classloader and current thread classloader can be used in loading a properties file for a J2EE application.
Using current classloader:
Using current thread context classloader:
References:
http://en.wikipedia.org/wiki/Classloader
R, Vladimir (2003). "Find a way out of the ClassLoader maze. System, current, context? Which ClassLoader should you use?"
javaworld.com. http://www.javaworld.com/javaworld/javaqa/2003-06/01-qa-0606-load.html. Retrieved on 2009-03-11.
0 comments:
Post a Comment