Class.getResource() 和 ClassLoader.getResource() 的区别

这篇博客详细解析了Java中Class.getResource()和ClassLoader.getResource()在加载资源时的不同。Class.getResource()会在路径前添加包名,而ClassLoader则不进行转换,两者都会委托ClassLoader查找资源,但Class的查找更适用于jar包内的资源。建议使用Class.getResource()来加载资源。

题记: 

       最近在加载资源文件的时候,碰到一些问题,也看了很多类似代码,发现有的在用Class.getResource() 加载资源,有些在用ClassLoader.getResource()加载资源,搞不清楚区别,最近学习了些资料,在此总结下;


提纲:

1  ClassLoader

     getResource()

     getResourceAsStream()

     getSystemResource()


2  Class

     getResource()

     getResourceAsStream()

     getSystemResource()


3 常用路径的资源加载方式


1.1  ClassLoader.getResource()

先看源代码:

 /**
     * Finds the resource with the given name.  A resource is some data
     * (images, audio, text, etc) that can be accessed by class code in a way
     * that is independent of the location of the code.
     *
     * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
     * identifies the resource.
     *
     * <p> This method will first search the parent class loader for the
     * resource; if the parent is <tt>null</tt> the path of the class loader
     * built-in to the virtual machine is searched.  That failing, this method
     * will invoke {@link #findResource(String)} to find the resource.  </p>     
     * 
     */
    public URL getResource(String name) {
        URL url;
        if (p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值