关于类加载的双亲委派机制的测试
作者:互联网
0.背景
最近又想到了双亲委派机制,然后决定做一个小实验来验证下理论。
于是有了接下来的测试。
1.测试
测试1:
创建一个User.java类,放在D:\\jc文件夹下
用 javac编译生成User.class文件
创建测试类Test
public class Test { public static void main(String[] args) throws Exception{ File file = new File("D:\\jc"); URL url = file.toURI().toURL(); ClassLoader loader1 = new URLClassLoader(new URL[]{url}); Class<?> clazz1 = loader1.loadClass("User"); System.out.println("当前类加载器" + clazz1.getClassLoader()); System.out.println("父类加载器" + clazz1.getClassLoader().getParent()); ClassLoader loader2 = new URLClassLoader(new URL[]{url}); Class<?> clazz2 = loader2.loadClass("User"); System.out.println("当前类加载器" + clazz2.getClassLoader()); System.out.println("父类加载器" + clazz2.getClassLoader().getParent()); System.out.println(clazz1 == clazz2); } }
输出
当前类加载器java.net.URLClassLoader@4b85612c 父类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 当前类加载器java.net.URLClassLoader@5c29bfd 父类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 false
测试2:
创建一个User.java类,放在D:\\jc文件夹下
用 javac编译生成User.class文件
创建测试类Test
public class Test { public static void main(String[] args) throws Exception{ File file = new File("D:\\jc"); URL url = file.toURI().toURL(); ClassLoader loader1 = new URLClassLoader(new URL[]{url}); Class<?> clazz1 = loader1.loadClass("User"); System.out.println("当前类加载器" + clazz1.getClassLoader()); System.out.println("父类加载器" + clazz1.getClassLoader().getParent()); //ClassLoader loader2 = new URLClassLoader(new URL[]{url}); Class<?> clazz2 = loader1.loadClass("User"); System.out.println("当前类加载器" + clazz2.getClassLoader()); System.out.println("父类加载器" + clazz2.getClassLoader().getParent()); System.out.println(clazz1 == clazz2); } }
输出
当前类加载器java.net.URLClassLoader@4b85612c 父类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 当前类加载器java.net.URLClassLoader@4b85612c 父类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 true
测试3:
在当前测试类Test的pakage下创建一个User.java(相当于在classpath下加载User类)
public class Test { public static void main(String[] args) throws Exception{ File file = new File("./"); URL url = file.toURI().toURL(); ClassLoader loader1 = new URLClassLoader(new URL[]{url}); Class<?> clazz1 = loader1.loadClass("com.ouym.test.User"); System.out.println("当前类加载器" + clazz1.getClassLoader()); System.out.println("父类加载器" + clazz1.getClassLoader().getParent()); ClassLoader loader2 = new URLClassLoader(new URL[]{url}); Class<?> clazz2 = loader2.loadClass("com.ouym.test.User"); System.out.println("当前类加载器" + clazz2.getClassLoader()); System.out.println("父类加载器" + clazz2.getClassLoader().getParent()); System.out.println(clazz1 == clazz2); } }
输出
当前类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 父类加载器sun.misc.Launcher$ExtClassLoader@4b85612c 当前类加载器sun.misc.Launcher$AppClassLoader@18b4aac2 父类加载器sun.misc.Launcher$ExtClassLoader@4b85612c true
2.实验总结
这是一次双亲委派模型的实验
对比实验1和实验2发现了什么?
对比实验1和实验3又发现了什么?
标签:委派,System,双亲,User,println,new,out,加载 来源: https://www.cnblogs.com/ouym/p/16578045.html