Different class loaders loading operation and effect analysis
-
Java Virtual Machine that comes with the loader (loop through output!)
public class MyTest13 { public static void main(String[] args) throws Exception { ClassLoader loader = ClassLoader.getSystemClassLoader(); System.out.println(loader); while (null!=loader){ loader = loader.getParent(); System.out.println(loader); } } } 运行结果: sun.misc.Launcher$AppClassLoader@18b4aac2 sun.misc.Launcher$ExtClassLoader@6d6f6e28 null
-
Example one:
- Gets the full path to the corresponding class file.
- Mainly for Jar hell problems and solutions:
- When multiple jar a class or a resource file exists, it will exist jar hell problem.
- You can diagnose a problem by the following code:
public class MyTest14 { public static void main(String[] args) throws Exception { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String resoureName = "Jvm/MyTest14.class"; Enumeration<URL> urls = loader.getResources(resoureName); while (urls.hasMoreElements()){ URL url = urls.nextElement(); System.out.println(url); } } } 运行结果: file:/E:/Program%20Files%20(x86)/IdeaProject/Javalearn/.../out/production/IdeaProject/Jvm/MyTest14.class
-
Ways to get the ClassLoader
//获取当前类的ClassLoaer clazz.getClassLoader(); //获取当前线程上下文的ClassLoader Thread.currentThread().getContextClassLoader(); //获得系统的ClassLoader ClassLoader.getSystemClassLoader(); //获取调用者的ClassLoader DriverManager.getCallerClassLoader();
-
Example 2:
-
MyTest14 custom class, the class loader loads the system; String type is located under rt.jar, the loaded class is loaded from the root
public class MyTest14 { public static void main(String[] args) throws Exception { Class<?> clazz1 = MyTest14.class; System.out.println(clazz1.getClassLoader()); Class<?> clazz2 = String.class; System.out.println(clazz2.getClassLoader()); } } 运行结果: sun.misc.Launcher$AppClassLoader@18b4aac2 null
-