简体   繁体   中英

Explicit loading - java.lang.ClassLoader

In first case, For explicit loading of test.ClassLoaderTest using below code,

public ClassLoaderTest{
      public static void main(String[] args){
        .....
        Class.forName("test.ClassLoaderTest", true,
                          ClassLoaderTest.class.getClassLoader().getParent());
        ....
      }

findClass() method of Launcher$ExtClassLoader instance gets invoked to load test.ClassLoaderTest with below error due to visibility principle,

java.lang.ClassNotFoundException: test.ClassLoaderTest
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at test.ClassLoaderTest.main(ClassLoaderTest.java:29)

In second case, On explicit loading of test.ClassLoaderTest1 , using

public ClassLoaderTest{
          public static void main(String[] args){
            .....
            Class.forName("test.ClassLoaderTest1");
            ....
          }

loadClass() method of Launcher$AppClassLoader instance is ultimately used to load test.ClassLoaderTest1 class,

where test.ClassLoaderTest1 is a wrong class file that lead to below error,

java.lang.ClassNotFoundException: test.ClassLoaderTest1
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at test.ClassLoaderTest1.main(ClassLoaderTest.java:16)

In both cases, class loading job is done by java.net.URLClassLoader.findClass()


Class.forName() internally invokes getClassLoader() to know the class loader that already loaded the class.

In second case, When Class gets a class loader instance(of type Launcher$AppClassLoader) by calling ClassLoader cl = getClassLoader0(); to invoke the class loader instance again.

Is java.lang.ClassLoader mainly used for sub-classing custom class loader? that load classes not available in CLASSPATH but from network source etc...

From the Javadoc,

public **abstract** class ClassLoader
extends Object

There are different ClassLoader implementations that use different strategies for locating and reading the byte streams that compose a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM