A.5. ClassLoader OptionsIn the Java API, you can explicitly use either the System (or Application), Current, or the Thread Context ClassLoader. You can access the System ClassLoader by calling ClassLoader.getSystemClassLoader( ). In most J2EE application servers, the System ClassLoader is too high in the hierarchy and will not find the resources packaged in your application's EJB JAR or WAR. In JBoss, using the System ClassLoader is still a problem because the ClassLoader Repository holds references to all deployed applications, so you could easily have a naming conflict if more than one application uses the same class. The Current ClassLoader is the ClassLoader that loaded the class that contains the method that's currently executing. Class.getResource( ) and the one-parameter version of Class.forName( ) use the Current ClassLoader by default. The Current ClassLoader is a better choice than the System ClassLoader, but there are still problems with using the Current ClassLoader:
You gain access to the current Thread Context ClassLoader by calling Thread.currentThread( ).getContextClassLoader( ). The Thread Context ClassLoader is the ClassLoader used by the creator of the Thread that runs your code. The Thread Context ClassLoader works in a way that's contrary to the Delegation Model by enabling a parent ClassLoader to access classes from any of its child ClassLoaders. Sometimes a parent ClassLoader needs to see classes that one of its child ClassLoaders instantiates at runtime. Use the Thread Context Class Loader for the following reasons:
Here are a couple of practical uses of the Thread Context ClassLoader:
|