What class loader is used?

I have a few questions regarding class loaders.

Class.forName("class.name"); 

and

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

What cool downloaders will be used in each case? In the first case, I assume the class loader, which was used to load the class in which the method code is executed. And in the second case, I assume the stream context class loader.

In case I am mistaken, a little explanation is appreciated.

+6
source share
1 answer

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.

+2
source

Source: https://habr.com/ru/post/921349/


All Articles