爲Class#getResourceAsStream(String)
的JavaDoc的寫着:Class如何找到資源?
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.
那麼,如何以下工作:
class AppTest {
private static final Properties p = new Properties();
static {
try {
p.load(AppTest.class.getResourceAsStream(("config.properties")));
} catch (IOException e) {
e.printStackTrace();
}
}
...
}
如果config.properties坐在同一個目錄中AppTest.class:
pro/wulfgar/net/on/users/app/{AppTest.class,config.properties}
不應該爲AppTest.class的類加載器在應用程序cla上尋找它sspath(在這種情況下爲.
)?因此config.properties應該與pro目錄處於同一級別。
也就是說,除非我將資源定義爲pro/wulfgar/net/on/users/app/config.properties
,否則我不明白爲什麼類加載器可以找到資源?
那麼它是否是AppTest.class的類加載器,最終將config.properties加載到jvm中?它只是在相同的包結構中搜索文件?如果我使用ClassLoader.getResourceAsStream,它會(而是)在父類或應用程序類加載器(引導程序,擴展等)中搜索config.properties,直到找到資源爲止。 – wulfgarpro
Class.getResourceAsStream只是給定調用類的包名稱(除非指定前導「/」)來簡單構造資源名稱。只需查看Class.getResourceAsStream的源代碼(例如使用Eclipse)。接下來發生的是類加載器實現(即是否首先檢查父類加載器資源) – gnomie