Thread.currentThread()。getContextClassLoader()



Thread Currentthread



スレッドスレッドAPI、 getContextClassLoader ()方法は次のとおりです。

RuntimePermission('getClassLoader')

大まかに中国語の意味に翻訳されます:



このスレッドのClassLoaderコンテキストを返します。 ClassLoaderがスレッドコードにクラスとリソースをロードするときに操作で使用できるようにするスレッドコンテキストを作成します。そうでない場合、デフォルトは親スレッドコンテキストClassLoaderを返します。元のスレッドコンテキストClassLoaderは通常、アプリケーションをロードするためにクラスローダーに設定されます。

まず、セキュリティマネージャがあり、呼び出し元のクラスローダーがnullでない場合、コンテキストクラスローダーが要求されているのは、その祖先スレッドのコンテキストクラスローダーとも異なります。checkPermissionセキュリティマネージャを呼び出す許可public class Test { public static void main(String[] args) { System.out.println(Thread.currentThread().getId()+'-outer:'+Thread.currentThread().getContextClassLoader()) new Thread(){ public void run(){ System.out.println(Thread.currentThread().getId()+'-inner:'+Thread.currentThread().getContextClassLoader()) } }.start() new Thread(){ public void run(){ System.out.println(Thread.currentThread().getId()+'-inner:'+Thread.currentThread().getContextClassLoader()) } }.start() } }メソッド、コンテキストClassLoaderを取得できるかどうかを確認します。



次の例は、親のClassLoader整合スレッドの子スレッドを示しています。

1-outer:root@xxxxx 12-inner:root@xxxxx 13-inner:root@xxxxx

戻り値:

* Returns the context ClassLoader for this Thread. The context * ClassLoader is provided by the creator of the thread for use * by code running in this thread when loading classes and resources. * If not {@linkplain #setContextClassLoader set}, the default is the * ClassLoader context of the parent Thread. The context ClassLoader of the * primordial thread is typically set to the class loader used to load the * application. * * 

If a security manager is present, and the invoker's class loader is not * {@code null} and is not the same as or an ancestor of the context class * loader, then this method invokes the security manager's {@link * SecurityManager#checkPermission(java.security.Permission) checkPermission} * method with a {@link RuntimePermission RuntimePermission}{@code * ('getClassLoader')} permission to verify that retrieval of the context * class loader is permitted.

これらの結果は、返されるClassLoaderが同じであることを示しています。



応用:

org.apache.commons.beanutils.BeanUtils#copyPropertiesソースを読んで、クラスorg.apache.commons.beanutils.ContextClassLoaderLocalを使用していることがわかりました。このクラスマップにより、JVMプログラムでClassLoaderがキー(上記の説明)として使用され、つまり、ClassLoaderはグローバルキーとして存在できます。