简体   繁体   中英

How is the system classloader in java useful?

I expect the system classloader to take over class loading for my application. So, if I run my program as,

java -Djava.system.class.loader=MyClassLoader Main

I expect Main to be loaded by MyClassLoader so that I can control class loading within my application. But that does not happen. Main is still loaded by the default system class loader (sun.misc.Launcher$AppClassLoader), as are other classes referenced from Main. However, calls to getSystemClassLoader() return an instance of MyClassLoader.

How is this useful? Wouldn't it make sense for Main to be loaded by my custom system class loader? How do I take control of class loading for my application? And who uses the getSystemClassLoader() value?

If you just subclassed URLClassLoader with no overriding, this is the documented behaviour you should expect :

The URLs will be searched in the order specified for classes and resources after first searching in the parent class loader.

If the parent class loader can load the class, then it does so, and the loader reported for that class will be the parent class loader. In order to revert this parent-first classloading policy that is the default for Java classloaders, you must override loadClass .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM