getContextClassLoader()
软件包java.lang.Thread.getContextClassLoader()中提供了此方法。
此方法用于返回此(当前)线程的上下文ClassLoader。
此方法不是静态的,因此该方法可通过Thread类对象访问,而无法通过类名称访问。
此方法的返回类型为ClassLoader,因此它返回上下文ClassLoader。
如果此线程未获取上下文ClassLoader,则此方法引发异常(SecurityException)。
语法:
ClassLoader getContextClassLoader(){
}
参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
该方法的返回类型为ClassLoader,它返回上下文ClassLoader。
getContextClassLoader()
方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class ContextClassLoader extends Thread {
//覆盖run()Thread类
public void run() {
//显示最终用户的消息
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
}
public static void main(String[] args) {
//创建一个ContextClassLoader类的对象
ContextClassLoader ccl = new ContextClassLoader();
//创建一个Thread类的对象
Thread th = new Thread(ccl);
//线程类start()方法将调用,并且最终
th.start();
// getContextClassLoader()将返回上下文ClassLoader-
//并创建ClassLoader的引用
ClassLoader cl = th.getContextClassLoader();
//通过使用setContextClassLoader(ClassLoader cl)设置
//此线程的上下文ClassLoader-
th.setContextClassLoader(cl);
System.out.println("The Context ClassLoader for this thread th is = " + cl);
System.out.println("The Parent of the ClassLoader is = " + cl.getParent());
System.out.println("The Class of the ClassLoader is = " + cl.getClass());
}
}
输出结果
E:\Programs>javac ContextClassLoader.java
E:\Programs>java ContextClassLoader
The Context ClassLoader for this thread th is = [email protected]
The name of this thread is Thread-1
The Parent of the ClassLoader is = [email protected]
The Class of the ClassLoader is = class sun.misc.Launcher$AppClassLoader