類載入器獲取資源路徑
阿新 • • 發佈:2019-01-05
一、同一工程中:
- 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(
- 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從當前類所在的目錄下開始查詢檔案
二、不同的工程中,實驗如下:
-
publicclass Sample2 {
- publicstaticvoid 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獲取的內容始終從呼叫方出發;而一般類的資源獲取是從類自身的位置觸發