Thread的getContextClassLoader()
忘记以前有没有问过这个问题,总之我现在有看到几个地方有这个:
Thread.currentThread().getContextClassLoader()
我总是想不出在什么情况下会用这种方式获得一个ClassLoader,因为好像默认情况下,它返回的是和加载应用的ClassLoader是同一个,比如说在一个类Test中写
ClassLoader cl = Thread.currentThread().getContextClassLoader();
为何不直接用Test.class.getClassLoader()
获得当前上下文的类加载器是啥意思?有啥好处?
[解决办法]
http://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream
[解决办法]
http://uule.iteye.com/blog/813841
[解决办法]
假设要装载的类,通过当前类的Classloader链装载不了,那就得设ContextClassLoader
[解决办法]
通过当前类的Classloader链装载不了,那就得设ContextClassLoader
[解决办法]
public class Test {
public static void main(String[] args) {
// 此时三个ClassLoader是同一个对象
System.out.println(Thread.currentThread().getContextClassLoader()); // 当前线程的类加载器
System.out.println(Test.class.getClassLoader()); // 当前类的类加载器
System.out.println(ClassLoader.getSystemClassLoader()); // 系统初始的类加载器
}
}
final ClassLoader parent = findParentClassLoader();
String libDirString = System.getProperty("openfire.lib.dir");
File libDir;
if (libDirString != null) {
// If the lib directory property has been specified and it actually
// exists use it, else use the default
libDir = new File(libDirString);
if (!libDir.exists()) {
Log.warn("Lib directory " + libDirString +
" does not exist. Using default " + DEFAULT_LIB_DIR);
libDir = new File(DEFAULT_LIB_DIR);
}
}
else {
libDir = new File(DEFAULT_LIB_DIR);
}
// Unpack any pack files.
unpackArchives(libDir, true);
String adminLibDirString = System.getProperty("openfireHome");
if (adminLibDirString == null) {
adminLibDirString = DEFAULT_ADMIN_LIB_DIR;
}
else {
adminLibDirString = adminLibDirString+"/plugins/admin/webapp/WEB-INF/lib";
}
File adminLibDir = new File(adminLibDirString);
if (adminLibDir.exists()) {
unpackArchives(adminLibDir, false);
}
else {
Log.warn("Admin Lib Directory " + adminLibDirString +
" does not exist. Web admin console may not work.");
}
ClassLoader loader = new JiveClassLoader(parent, libDir);
Thread.currentThread().setContextClassLoader(loader);
Class containerClass = loader.loadClass(
"org.jivesoftware.openfire.XMPPServer");
containerClass.newInstance();