ClassLoader类加载器探索ing...

类加加载器加载类型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);
    }
}

后续补充中…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值