區別:Thread.currentThread().getContextClassLoader() and Class.getClassLoader()

打個簡單的比方,你一個WEB程序,發佈到Tomcat裏面運行。
首先是執行Tomcat org.apache.catalina.startup.Bootstrap類,這時候的類加載器是ClassLoader.getSystemClassLoader()。
而我們後面的WEB程序,裏面的jar、resources都是由Tomcat內部來加載的,所以你在代碼中動態加載jar、資源文件的時候,首先應該是使用Thread.currentThread().getContextClassLoader()。如果你使用Test.class.getClassLoader(),可能會導致和當前線程所運行的類加載器不一致(因爲Java天生的多線程)。如果在另一個運行的Test.class.getClassLoader在另一個線程中可能有問題
Test.class.getClassLoader()一般用在getResource,因爲你想要獲取某個資源文件的時候,這個資源文件的位置是相對固定的。

java的類加載機制(jvm規範)是委託模型,簡單的說,如果一個類加載器想要加載一個類,首先它會委託給它的parent去加載,如果它的所有parent都沒有成功的加載那麼它纔會自己親自來,有點兒像兒子使喚老子的感覺。

 

如果你使用Test.class.getClassLoader(),可能會導致和當前線程所運行的類加載器不一致 :Class.getClassLoader() returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章