javaclassloadercontextclassloader

what class loader is used?


I have several questions regarding to class loaders.

Class.forName("class.name");

and

....
NotYetLoadedClass cls = new NotYetLoadedClass();
.....

What class loaders will be used in each case? For the first case I assume class loader that was used to load class in which method code is executing. And in the second case I assume thread context class loader.

In case I am wrong, a small explanation is appreciated.


Solution

  • Both use the current ClassLoader. As DNA correctly points out, http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#forName%28java.lang.String%29 states that Class.forName() uses the current class loader. A little experiment shows that a class loaded for instantiation using the new statement also uses the current ClassLoader:

    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            Thread.currentThread().setContextClassLoader(new MyClassLoader());
            SomeClass someClass = new SomeClass();
            someClass.printClassLoader();
        }
    
        public static class MyClassLoader extends ClassLoader
        {
            public MyClassLoader()
            {
                super();
            }
    
            public MyClassLoader(ClassLoader parent)
            {
                super(parent);
            }
        }
    }
    
    
    
    public class SomeClass
    {
        public void printClassLoader()
        {
            System.out.println(this.getClass().getClassLoader());
            System.out.println(Thread.currentThread().getContextClassLoader());
        }
    }
    

    In Test we set the current's thread ContextClassLoader to some custom ClassLoader and then instantiate an object of class SomeClass. In SomeClass we print out the current thread's ContextClassLoader and the ClassLoader that loaded this object's class. The result is

    sun.misc.Launcher$AppClassLoader@3326b249
    test.Test$MyClassLoader@3d4b7453
    

    indicating that the current ClassLoader (sun.misc.Launcher.AppClassLoader) was used to load the class.