一、類加載器的層次結構java
在雙親委託機制中,各個加載器按照父子關係造成了樹形結構(邏輯意義),除了根加載器以外,其他的類加載器都有且只有一個父加載器。jvm
public class MyTest13 { public static void main(String[] args) { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); System.out.println(classLoader); while (null != classLoader){ classLoader = classLoader.getParent(); System.out.println(classLoader); } } }
打印結果ui
sun.misc.Launcher$AppClassLoader@18b4aac2 sun.misc.Launcher$ExtClassLoader@1540e19d null
null說明classLoader是啓動類加載器url
二、類加載器的雙親委託機制spa
三、返回String類的ClassLoader線程
public class MyTest7 { public static void main(String[] args) throws Exception{ Class<?> clazz = Class.forName("java.lang.String"); ClassLoader classLoader = clazz.getClassLoader(); System.out.println(classLoader); } }
返回結果blog
null
null說明classLoader是啓動類加載器ssl
四、返回自定義類的ClassLoaderget
public class MyTest7 { public static void main(String[] args) throws Exception{ Class<?> clazz2 = Class.forName("com.example.jvm.classloader.C"); ClassLoader classLoader2 = clazz2.getClassLoader(); System.out.println(classLoader2); } } class C{ }
返回結果io
sun.misc.Launcher$AppClassLoader@18b4aac2
五、得到class文件的路徑
public class MyTest14 { public static void main(String[] args) throws IOException{ ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); System.out.println(classLoader); String resourceName = "com/example/jvm/classloader/MyTest13.class"; Enumeration<URL> urls = classLoader.getResources(resourceName); while (urls.hasMoreElements()){ URL url = urls.nextElement(); System.out.println(url); } } }
打印結果:
sun.misc.Launcher$AppClassLoader@18b4aac2 file:/D:/workspace/study/%20jvm_demo/build/classes/java/main/com/example/jvm/classloader/MyTest13.class
六、得到ClassLoader的途徑
得到當前類的ClassLoader
clazz.getClassLoader();
得到當前線程的上下文ClassLoader
Thread.currentThread().getContextClassLoader()
得到系統的ClassLoader
ClassLoader.getSystemClassLoader();
得到調用者的ClassLoader
DriverManager.getCallerClassLoader()