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 claims that Class.forName()
uses the current class loader. A small experiment shows that a class loaded to create an instance using the new
operator 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 ContextClassLoader stream to some custom ClassLoader
, and then instantiate an object of the SomeClass
class. In SomeClass
we print the current thread, ContextClassLoader and ClassLoader
, which loaded this object 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.
source share