Java 反射机制详解(二)

Java 反射机制详解(二)

 2.ClassLoader

 类装载器是用来把类(class)装载进 JVM 的,JVM 规范定义了两种类型的类装载器:启动类装载器(bootstrap)和用户自定义装载器(user-defined class loader)。 JVM在运行时会产生3个类加载器组成的初始化加载器层次结构 ,如下图所示:

 

public class ReflectionTest {
    @Test
    public void testClassLoader() throws ClassNotFoundException, FileNotFoundException{
        //1. 获取一个系统的类加载器(可以获取,当前这个类PeflectTest就是它加载的)
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        System.out.println(classLoader);
        

        //2. 获取系统类加载器的父类加载器(扩展类加载器,可以获取). 
        classLoader = classLoader.getParent();
        System.out.println(classLoader); 
        

        //3. 获取扩展类加载器的父类加载器(引导类加载器,不可获取).
        classLoader = classLoader.getParent();
        System.out.println(classLoader);
        

        //4. 测试当前类由哪个类加载器进行加载(系统类加载器): 
        classLoader = Class.forName("com.atguigu.java.fanshe.ReflectionTest")
             .getClassLoader();
        System.out.println(classLoader);
    

        //5. 测试 JDK 提供的 Object 类由哪个类加载器负责加载(引导类)
        classLoader = Class.forName("java.lang.Object")
                 .getClassLoader();
        System.out.println(classLoader); 
    }
}
//结果:
//sun.misc.Launcher$AppClassLoader@5ffdfb42
//sun.misc.Launcher$ExtClassLoader@1b7adb4a
//null
//sun.misc.Launcher$AppClassLoader@5ffdfb42
//null

使用类加载器获取当前类目录下的文件 

 

首先,系统类加载器可以加载当前项目src目录下面的所有类,如果文件也放在src下面,也可以用类加载器来加载,调用 getResourceAsStream 获取类路径下的文件对应的输入流

 

public class ReflectionTest {
    @Test
    public void testClassLoader() throws FileNotFoundException{
        //src目录下,直接加载
        InputStream in1 = null;
        in1 = this.getClass().getClassLoader().getResourceAsStream("test1.txt");
        
        //放在内部文件夹,要写全路径
        InputStream in2 = null;
        in2 = this.getClass().getClassLoader().getResourceAsStream("com/atguigu/java/fanshe/test2.txt");
    }
}

原文链接:https://www.cnblogs.com/tech-bird/p/3525336.html

猜你喜欢

转载自blog.csdn.net/nioqnw/article/details/84618919