BootStrap
Extension
App
自定义
以上4个加载器, 怎么写出一个'正常'程序,但是类加载不了, 提示 class not found ,必须自定义类加载
或者
使用这种加载Thread.currentThread().setContextClassLoader(extensionLoader);
为什么需要自定义的 classloader??
引用:
举一个简单的例子: 假如某天JAVA给我们提供了一个叫 StartCamera 的类用来启动电脑的标准摄像头,并将这个类打包在一个jar中。 正常情况下,我们要启动摄像头时只需将这个jar配置到classpath中。系统启动时system classloader会将这个类加载到应用中。 但因为摄像头的生产厂家不一样,针对新的设备会有多个不同的StartCamera实现,在应用中我们不知道实际的用户会用到哪种。于是我们就自定义了一个ClassLoader,用来针对具体的设备类型加载相应的StartCamera类。 这样一来就出现:优先加载我们定义的类,加载不到的情况下再加载系统的。 这样的需求,是系统默认的父委托加载机制无法满足的。 Thread.currentThread.getContextClassLoader() 就是这样产生的。 我们使用Thread.currentThread.setContextClassLoader() 可以为当前线程指定相应的ClassLoader,然后用get的方式来获取。
private void initSpringContext() {
if(this.cokExtension == null){
return;
}
ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
ClassLoader extensionLoader = getClass().getClassLoader();
Thread.currentThread().setContextClassLoader(extensionLoader);
GenericXmlApplicationContext newContext = new GenericXmlApplicationContext(new
ClassPathResource("test1.xml", extensionLoader),
new ClassPathResource("test2.xml", extensionLoader));
Thread.currentThread().setContextClassLoader(origLoader);
if(context != null){
context.close();
}
context = newContext;
}
上边这块是项目中用到的一块,不知道为什么搞这个getClass().getClassLoader() 替换Thread.currentThread().getContextClassLoader();
除非你把打完的jar包里的某个类正好删了,不然类都存在情况下,显然不会出现class not found啊,不是这么玩的
比如说你自定classloader,只扫描加载你所指定的类,你可以在里面自己做文章。 这是自定义Classloader的作用。
Thread.currentThread().setContextClassLoader(extensionLoader); 就是说你要使用哪个classloader去加载。
默认就是默认的双亲委派机制。