一、同一工程中:
- String path = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
- System.out.println(path);
- String string = Sample1.class.getClassLoader().getResource(".").getPath();
- System.out.println(string);
- String string2 = Sample1.class.getResource(".").getPath();
- System.out.println(string2);
测试结果:
- /D:/workspaces/workspace7/demo1/target/classes/
- /D:/workspaces/workspace7/demo1/target/classes/
- /D:/workspaces/workspace7/demo1/target/classes/com/alibaba/
说明:
Classloader读取文件(即方式1和方法2)都是从classpath开始查找文件; 方式3从当前类所在的目录下开始查找文件
二、不同的工程中,实验如下:
- public class Sample2 {
- public static void main(String[] args) {
- Sample1 sample1 = new Sample1();
- sample1.print();
- }
- }
执行结果:
- /D:/workspaces/workspace7/demo2/target/classes/
- /D:/workspaces/workspace7/demo2/target/classes/
- /D:/workspaces/workspace7/demo1/target/classes/com/alibaba/
说明:Classloader获取的内容始终从调用方出发; 而一般类的资源获取是从类自身的位置触发