6

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?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
user10777718
  • 723
  • 4
  • 16

1 Answers1

3

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 1
    For example, classloaders will be different for the Spring Boot application, if you run repackaged jar. Spring Boot uses LaunchedURLClassLoader. SystemClassLoader doesn't know about new classes location inside the repackaged jar file thus it cannot load any resources from resources folder. – Alexander Radchenko Mar 30 '22 at 13:53