I\'m trying to override the system\'s class loader using the flag -Djava.system.class.loader=MyLoader
. However, MyLoader
is still not being used w
The Javadoc of Class.forName(String) states (emphasis mine):
Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to: Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class.
In other words, the method doesn't automatically use the system classloader - it uses the loader that physically defined the class from which it's called. From the Java language spec, section 5.3:
A class loader L may create C by defining it directly or by delegating to another class loader. If L creates C directly, we say that L defines C or, equivalently, that L is the defining loader of C.
Your custom classloader doesn't create the Main
class directly - it delegates to the parent loader to create the class, so it's that parent classloader that will be used when you call Class.forName(String)
in a method of Main
. If you want to use your custom classloader directly, you'll need to either explicitly specify it using the 3-arg variant of Class.forName
or alter your custom classloader implementation so that it actually loads the class in question (typically by extending URLClassLoader
).