Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement System Classloader for Classes In Jars containing Jars

So far, the examples I have seen for custom ClassLoaders involve subclassing the URLClassLoader, and using that specific instance to load classes in resources.

I have tried in vain to look for alternative methods to replace the SystemClassLoader, so that my ClassLoader can be consulted for classes not located in the classpath.

I tried Thread.currentThread().setContextClassLoader, but it doesn't seem to work.

Is it even possible?

like image 924
Olaseni Avatar asked Mar 21 '11 16:03

Olaseni


People also ask

How do you find the ClassLoader of a class?

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 are different types of ClassLoader?

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.

Which ClassLoader is used to load a class?

Types of ClassLoaders in Java 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.

Which ClassLoader loads JAR files from JDK?

The Bootstrap class loader loads the basic runtime classes provided by the JVM, plus any classes from JAR files present in the system extensions directory. It is parent to the System class loader. To add JAR files to the system extensions, directory, see Using the Java Optional Package Mechanism.


1 Answers

Though this is an old question, there is indeed a way to replace the system ClassLoader. You might get more than you bargained for, however, with reflection.

        Field scl = ClassLoader.class.getDeclaredField("scl"); // Get system class loader
        scl.setAccessible(true); // Set accessible
        scl.set(null, new YourClassLoader()); // Update it to your class loader

This should work on the Oracle JVM.

like image 80
Xyene Avatar answered Oct 29 '22 05:10

Xyene