2016-10-04 62 views
1

有人能告訴我什麼時候在web應用程序中使用Thread.currentThread().getContextClassLoader() 。請給我提供一些真實生活的例子。請不要將它標記爲重複的問題(我的問題是何時使用Thread.currentThread()。getContextClassLoader(),而不是用於加載屬性文件)。我經歷了很多網站,但沒有得到正確的答案。什麼時候在web應用程序中使用Thread.currentThread()。getContextClassLoader()

回答

2

首先,請注意,這種方法不是Java EE相關的東西,它是Java SE的一種方法,所以它不是僅用於Web應用程序,而是可能用於任何Java應用程序的東西。

我們通常使用此方法與Thread.currentThread().setContextClassLoader(ClassLoader)以檢查和/或更改調用線程的上下文ClassLoader

所以,通常我們說,你正在寫一個Java應用程序,將需要一個定製ClassLoader,從特定的文件夾和/或jar文件加載類,其中最初沒有在類路徑中,你可以使用這些方法來改變背景ClassLoader的並恢復以前的CL。這將允許您的代碼訪問那些以前不能從當前上下文CL訪問的類,因爲它們最初不在類路徑中。

因此,這裏是你的代碼會是什麼樣子:

// The previous context ClassLoader 
final ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); 
try { 
    // Set my custom ClassLoader to make my classes accessible 
    Thread.currentThread().setContextClassLoader(myCustomCL); 
    // Execute some code here that will be able to access to classes or resources from 
    // my specific folders and/or jar files 

} finally { 
    // Restore the previous CL 
    Thread.currentThread().setContextClassLoader(contextCL); 
} 
相關問題