Java Thread getContextClassLoader()方法

2019-10-16 22:24:55

Thread類的getContextClassLoader()方法返回執行緒的上下文ClassLoader

語法

public ClassLoader getContextClassLoader()

返回

  • 它返回執行緒的上下文ClassLoader

異常

  • SecurityException:如果當前執行緒無法獲取上下文ClassLoader

範例

public class JavaGetClassLoaderExp implements Runnable   
{  
    public void run()   
    {  
        System.out.println("Thread is running");  
    }  
    public static void main(String args[])  
    {  
        JavaGetClassLoaderExp g1 = new JavaGetClassLoaderExp();  
        Thread t1 = new Thread(g1);  
        // call run() method  
        t1.start();  

        // returns the context ClassLoader for thread t1  
        ClassLoader loader = t1.getContextClassLoader();  
        // sets the context ClassLoader for thread t1   
        t1.setContextClassLoader(loader);  
        System.out.println("Context ClassLoader = " + loader);  
        System.out.println("Parent = " + loader.getParent());  
        System.out.println("Class = " + loader.getClass());  
    }  
}

執行上面範例程式碼,得到以下結果:

Context ClassLoader = jdk.internal.loader.ClassLoaders$AppClassLoader@7c53a9eb
Parent = jdk.internal.loader.ClassLoaders$PlatformClassLoader@ed17bee
Class = class jdk.internal.loader.ClassLoaders$AppClassLoader
Thread is running