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?
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.
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.
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.
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.
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.
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