Why is custom system classloader not working?

前端 未结 2 1037
名媛妹妹
名媛妹妹 2020-12-11 05:40

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 06:20

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

提交回复
热议问题