Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassLoader.getSystemClassLoader() vs obj.getClass().getClassLoader().getSystemClassLoader()

Are these exactly same:

ClassLoader.getSystemClassLoader() // 1

vs:

obj.getClass().getClassLoader().getSystemClassLoader() // 2
Person.class.getClassLoader().getSystemClassLoader()

Is there a situation possible where they could yield different results?

like image 321
user10777718 Avatar asked Oct 16 '22 08:10

user10777718


1 Answers

As per ClassLoader.getSystemClassLoader() javadoc this is normally the class loader used to start the application. The java.system.class.loader property can be used to override the returned class loader, however:

The system property to override the system class loader is not examined until the VM is almost fully initialized. Code that executes this method during startup should take care not to cache the return value until the system is fully initialized.

In more complex setups obj.getClass().getClassLoader() or Person.class.getClassLoader() can return a custom class loader e.g. OSGI. It's entirely up to this custom class loader to return the system class loader. It might choose not e.g. because it would bypass the OSGI boundle class loading boundaries, see this answer.

So most of the time they should be the same, but nothing stops you from configuring the JVM or writing software that would make them different.

like image 72
Karol Dowbecki Avatar answered Oct 21 '22 00:10

Karol Dowbecki