akula1001
akula1001

Reputation: 4636

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?

Upvotes: 1

Views: 687

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

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.

Upvotes: 1

Related Questions