类加加载器加载类型Demo
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()); //系统初始的类加载器
}
}
说明:
可以通过了解openfire对ClassLoader加深理解。
例如: 一个WEB程序,发布到Tomcat里面运行。
首先是执行Tomcat org.apache.catalina.startup.Bootstrap类,这时候的类加载器是ClassLoader.getSystemClassLoader()。
而我们后面的WEB程序,里面的jar、resources都是由Tomcat内部来加载的,所以在代码中动态加载jar、资源文件的时候,首先应该是使用Thread.currentThread().getContextClassLoader()。如果使用Test.class.getClassLoader(),可能会导致和当前线程所运行的类加载器不一致(因为Java天生的多线程)。
Test.class.getClassLoader()一般用在getResource,因为你想要获取某个资源文件的时候,这个资源文件的位置是相对固定的。
建议查看一下openfire或者tomcat内部的源码,对ClassLoader会有比较深的理解。
在openfire里面,openfire使用的类加载器,以及每个插件使用的类加载器都不一样。
实例运用:获取properties文件内容
public class Test{
private static Properties props = new Properties();
static {
try {
//获得当前上下文类加载器取得properties文件相对于classPath的路径(实际上也是绝对路径)
props.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("conf/alipay.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//获取properties文件内容
public static String getContext(String key) {
return props.getProperty(key);
}
}
后续补充中…