user10777718
user10777718

Reputation: 743

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?

Upvotes: 6

Views: 1637

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

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.

Upvotes: 3

Related Questions