13_不同的类加载器作用与加载动作分析
类加载器结构
代码:
public class MyTest13 {
public static void main(String[] args) {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
System.out.println("classLoader = " + classLoader);
while (null!=classLoader){
classLoader = classLoader.getParent();
System.out.println("classLoader = " + classLoader);
}
}
}
输出:
classLoader = sun.misc.Launcher$AppClassLoader@58644d46
classLoader = sun.misc.Launcher$ExtClassLoader@4554617c
classLoader = null
从javadoc可知,HotSpot中classLoader为null表示BootStrap类加载器。
获得ClassLoader的途径
代码:
public class MyTest14 {
public static void main(String[] args) throws IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String resourceName = "top/tomxwd/classloader/MyTest13.class";
Enumeration<URL> urls = classLoader.getResources(resourceName);
while (urls.hasMoreElements()){
URL url = urls.nextElement();
System.out.println(url);
}
System.out.println("--------------------");
Class<?> clazz = MyTest14.class;
System.out.println("clazz.getClassLoader() = " + clazz.getClassLoader());
System.out.println("--------------------");
clazz = String.class;
System.out.println("clazz.getClassLoader() = " + clazz.getClassLoader());
}
}
输出:
file:/E:/IDEA-workspace/jvm-test-01/target/classes/top/tomxwd/classloader/MyTest13.class
--------------------
clazz.getClassLoader() = sun.misc.Launcher$AppClassLoader@58644d46
--------------------
clazz.getClassLoader() = null
评论区