// 获取系统类加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
// systemClassLoader: sun.misc.Launcher$AppClassLoader@73d16e93
// 获取其上层:拓展类加载器
ClassLoader extClassLoader = systemClassLoader.getParent();
// extClassLoader: sun.misc.Launcher$ExtClassLoader@12028586
// 获取拓展类载器上层
ClassLoader bootstrapClassLoader = extClassLoader.getParent();
// bootstrapClassLoader: null 获取不到引导类加载器
//对于用户自定义类,默认使用系统类加载器进行加载
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
//classLoader: sun.misc.Launcher$AppClassLoader@73d16e93
// String 使用引导类加载器加载
ClassLoader classLoaderString = String.class.getClassLoader();
// classLoaderString: null --> Java 核心类库使用引导类加载器加载
加载器加载路径:
// 获取启动类加载器加载路径
URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
for (URL url : urls) {
System.out.println(url.toExternalForm());
}
/*
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/resources.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/rt.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/sunrsasign.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/jsse.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/jce.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/charsets.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/lib/jfr.jar
file:/C:/Software/java/.jdks/jdk1.8.0_251/jre/classes
*/
// 获取扩展类加载器加载目录
String extDirs = System.getProperty("java.ext.dirs");
for (String s : extDirs.split(";")) {
System.out.println(s);
}
/*
C:\Software\java\.jdks\jdk1.8.0_251\jre\lib\ext
C:\Windows\Sun\Java\lib\ext
*/
获取ClassLoader:
// 获取当前类的ClassLoader
clazz.getClassLoader()
// 获取当前线程上下文的ClassLoader
Thread.currentThread().getContextClassLoader()
// 获取系统的ClassLoader
ClassLoader.getSystemClassLoader()
// 获取调用者的ClassLoader
DriverManager.getCallerClassLoader()