Stock JDK classes and the “null” ClassLoader?

后端 未结 3 1660
南笙
南笙 2020-12-20 16:39

Hi guys : Im trying to debug a very strange class error by looking at the ClassLoaders for some dynamically created components. ClassLoaders are s

相关标签:
3条回答
  • 2020-12-20 17:17

    This is how it works . Whenever JVM try to load any class it's checks below conditions.

    If Class is loaded from Bootstrap ClassPath i.e; jdk\jre\lib\rt.jar , BootStrap ClassLoader will be called.

    If Class is loaded from Extension Classpath i.e; jdk\jre\lib\ext*.jar , Extension ClassLoader will be called.

    If Class is loaded from Application ClassPath i.e; as specified in Environment Variable , Application ClassLoader is called .

    Since Bootstrap ClassLoader is not implemented in java , it's either implemented in c or c++ so there is no reference for it that's why it returns null . But Extension and Application class Loader is written in java so you will get the reference as sun.misc.Launcher$ExtClassLoader@someHexValue and sun.misc.Launcher$AppClassLoader@someHexValue .

    So, if you do something like this System.out.println(String.class.getClassLoader()) you will get null since this class is been called by BootStrap ClassLoader, On the other hand if you do the same thing for a class in Ext or App Class path you will get $ExtClassLoader@someHexValue and sun.misc.Launcher$AppClassLoader@someHexValue respectively .

    0 讨论(0)
  • 2020-12-20 17:20

    Classloader of the bootstrap classes is null, it's not a java class.

    Do not mistake the classes found of the classpath and the ones loaded by the bootstrap loader. The latter is responsible for the core JDK classes usually found in rt.jar. It's a native classloader, hence no reference towards.

    The classes on the classpath are loaded by the System classloader, and the class of it can be specified via property.

    Morealso the null classloader is considered a security issue and there are checks based on the caller class having null classloader.

    0 讨论(0)
  • 2020-12-20 17:37

    The javadoc for getClassLoader() says

    Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

    So, that at least explains why you get that result. But it does not explain why the implementors decided to do it that way.

    EDIT: After testing adding my own classes to the bootclasspath then they also show up as null class loader.

    0 讨论(0)
提交回复
热议问题