public class ClassLoaderTest { public static void main(String[] args) { //获取系统类加载器 ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); System.out.println(systemClassLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2 //获取其上层:扩展类加载器 ClassLoader extClassLoader = systemClassLoader.getParent(); System.out.println(extClassLoader);//sun.misc.Launcher$ExtClassLoader@1b6d3586 //获取其上层。:获取不到引导类加载器 ClassLoader bootstrapClassLoader = extClassLoader.getParent(); System.out.println(bootstrapClassLoader);//null //对于用户自定义类来所,他的类加载器是什么 ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); System.out.println(classLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2 //String类使用引导类加载器进行加载--》Java的核心类库都是使用引导类加载器的 ClassLoader strclassLoader = String.class.getClassLoader(); System.out.println(strclassLoader); } }
启动类加载器(引导类加载器-Bootstrap ClassLoader)
扩展类加载器Extension ClassLoader
应用程序类加载器(系统类加载器 AppClassLoader)
public class ClassLoaderTest1 { public static void main(String[] args) { System.out.println("##################启动类加载器"); //获取BootstrapClassLoader能够加载的api的路径 URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs(); for (URL url : urls) { System.out.println(url.toExternalForm()); } /** * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/rt.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/sunrsasign.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/jsse.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/jce.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/charsets.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/lib/jfr.jar * file:/C:/Program%20Files/Java/jdk1.8.0_202/jre/classes */ //从上面路径种随意选择一个类,看看其类加载器是什么 ClassLoader classLoader = Provider.class.getClassLoader(); System.out.println(classLoader);//null ,代表是引导类加载器 System.out.println("#################扩展类加载器"); String extDirs = System.getProperty("java.ext.dirs"); for (String path : extDirs.split(";")){ System.out.println(path); } /** * #################扩展类加载器 * C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext * C:\WINDOWS\Sun\Java\lib\ext */ //随便挑一个,看看类加载器 ClassLoader classLoader1 = CurveDB.class.getClassLoader(); System.out.println(classLoader1);//sun.misc.Launcher$ExtClassLoader@4b67cf4d } }
用户自定义类加载器
ClassLoader是什么
获取ClassLoader的方式:
public class ClassLoaderTest2 { public static void main(String[] args) { try { //1获取当前类String的加载器 ClassLoader classLoader = Class.forName("java.lang.String").getClassLoader(); System.out.println(classLoader);//null //2获取当前线程上下文ClassLoader ClassLoader classLoader1 = Thread.currentThread().getContextClassLoader(); System.out.println(classLoader1);//sun.misc.Launcher$AppClassLoader@18b4aac2 //3获取系统加载器 ClassLoader classLoader2 = ClassLoader.getSystemClassLoader(); System.out.println(classLoader2);//sun.misc.Launcher$AppClassLoader@18b4aac2 } catch (ClassNotFoundException e) { e.printStackTrace(); } } }