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

本秂侑毒 提交于 2019-12-01 21:39:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/54037306/classloader-getsystemclassloader-vs-obj-getclass-getclassloader-getsystemc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!