Thread
類的setContextClassLoader()
方法為執行緒設定上下文ClassLoader
。 建立執行緒時可以設定上下文ClassLoader
。 它允許執行緒的建立者通過getContextClassLoader
為載入類和資源時線上程中執行的程式碼提供適當的類載入器。
語法
public void setContextClassLoader(ClassLoader cl)
引數
cl
:它是Thread
類的上下文ClassLoader
。返回
異常
SecurityException
:如果當前執行緒無法設定上下文ClassLoader
。範例
public class JavaSetClassLoaderExp implements Runnable
{
public void run()
{
System.out.println("Thread is running");
// returns the context ClassLoader for currently running thread
ClassLoader loader = Thread.currentThread().getContextClassLoader();
// sets the context ClassLoader for currently running thread
Thread.currentThread().setContextClassLoader(loader);
System.out.println("Context ClassLoader = " + loader);
}
public static void main(String args[])
{
JavaSetClassLoaderExp g1 = new JavaSetClassLoaderExp();
Thread t1 = new Thread(g1);
// call run() method
t1.start();
}
}
執行上面範例程式碼,得到以下結果:
Thread is running
Context ClassLoader = sun.misc.Launcher$AppClassLoader@4e0e2f2a