您的位置:首页 > 其它

关于Class.getResource与Class.getClassLoader.getResource的区别

2013-01-04 16:20 302 查看
1, ClassLoader.getResource() 的api文档解释:

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.
The name of a resource is a '/'-separated path name that identifies the resource.
This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.


大致意思是,寻找给定名称的资源。该资源可以是一些可以被代码以一种无关代码位置的方式访问的数据(如图片,音频,文档等)
该名称以“/”分割符分割。
该方法首先搜索父类加载器的资源,如果父类加载器为空,则虚拟机内建类加载器执行搜索
其中的搜索路径是类加载器的加载路径,即classpath可以通过System.getProperty("java.class.path")获得,通常为工程中的bin目录(class文件所在的主目录)
实例:如下目录结构

当在IOManager中执行如下代码时

this.getClass().getClassLoader().getResource("");输入bin目录的路径
this.getClass().getClassLoader().getResource("");为空
this.getClass().getClassLoader().getResource("resources/config/common.properties");
this.getClass().getClassLoader().getResource("/resources/config/common.properties");为空


2, Class.getResource()的api文档解释:

Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource.
Before delegation, an absolute resource name is constructed from the given resource name using this                          algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').


大致意思就是,寻找给定名称的资源。对于一个与给定类关联的资源的搜索规则是通过该类的类加载器实现的。该方法委托对象的类加载器实现搜索。如果该对象是被bootstrap类加载器加载,则该方法通过ClassLoader.getSystemResource实现。
在委托搜索前,一个绝对资源名是通过以下算法构造:
1)如果资源名是以“/”开头,则该资源的绝对名为“/”后的部分
2)否则,资源的绝对名称即为modified_package_name/name,其中modified_package_name为class对象包名
举个例子:目录结构如上图
当在IOManager中有如下代码是则会加载与其同目录的comon.properites资源文件

this.getClass().getResource("common.properties");
或者
this.getClass().getResource("/helios/facility/files/common.properties");
而如下代码则无法加载
this.getClass().getResource("/common.properties");


这是因为当为/common.properties时,该方法会委托该类的类加载器去搜索该classpath(bin目录, 前面已说明)下的common.properties

Where the modified_package_name is the package name of this object with '/' substituted
for '.' ('\u002e').
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐