做了一个关于URLClassLoader和Thread context classloader的实验,大概也能总结出一些东东来。
工程目录:
代码如下:
Main类:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String jarName = "E://hotyeWorkspace//webterminal//terminal-dm-server//repository//06-other//osp-mina-client-for-terminal.jar";
File file = new File(jarName);
System.out.println("file = " + file);
URL[] urls = new URL[]{file.toURI().toURL()};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class<?> c = urlClassLoader.loadClass("com.hotye.osp.core.pojo.GnetBaseBean");
System.out.println("c = " + c);
Object o = c.newInstance();
System.out.println("o = " + o);
System.out.println("class classloader = " + Main.class.getClassLoader());
System.out.println("thread classloader = " + Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(urlClassLoader);
System.out.println("thread classloader = " + Thread.currentThread().getContextClassLoader());
new ThreadOne().start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ThreadOne类:
public class ThreadOne extends Thread {
public ThreadOne(){
System.out.println("ThreadOne classloader = "+this.getClass().getClassLoader());
System.out.println("ThreadOne thread classloader = "+Thread.currentThread().getContextClassLoader());
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("ThreadOne run...");
}
}
输出:
file = E:\hotyeWorkspace\webterminal\terminal-dm-server\repository\06-other\osp-mina-client-for-terminal.jar
c = class com.hotye.osp.core.pojo.GnetBaseBean
o = com.hotye.osp.core.pojo.GnetBaseBean@61de33
class classloader = sun.misc.Launcher$AppClassLoader@19821f
thread classloader = sun.misc.Launcher$AppClassLoader@19821f
thread classloader = java.net.URLClassLoader@c17164
ThreadOne classloader = sun.misc.Launcher$AppClassLoader@19821f
ThreadOne thread classloader = java.net.URLClassLoader@c17164
ThreadOne run...
结论:从实验可以看出,ThreadOne线程类也是类,所以它的类加载器继承了new它的类Main类,所以是AppClassLoader。而Thread context classloader也继承了Main类的Thread context classloader。感觉
Thread context classloader就是一个变量用来存储classloader的,除了书上说的加载jdbc那些驱动类要用到这个classloader之外,其余地方还没见到,可能多线程有用到吧,这些以后还要慢慢研究。
连接一片classloader文章:http://java.chinaitlab.com/base/839358_2.html