首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

getClassLoader().getResource()跟getResource()的区别

2013-11-29 
getClassLoader().getResource()和getResource()的区别eg:TemplateCode.class.getClass().getClassLoader(

getClassLoader().getResource()和getResource()的区别

eg:
   TemplateCode.class.getClass().getClassLoader().getResource("foo/bar.txt")

   TemplateCode.class.getClassLoader().getResource("foo/bar.txt")的区别

第二句话实际上还是调用的第一句,
区别在于第一句话不能以/开始,并总是从classpath的根目录开始查找,
第二句如果以/开始,则从根目录开始查找,如果开始不加/则从当前类所在的路径开始查找

验证通过

参考原文

http://stackoverflow.com/questions/14739550/what-is-the-difference-between-getclass-getclassloader-getresource-and-get

引用The second one calls the first one. The difference is described in the javadoc.

The first one takes paths that don't start with a /, and always starts at the root of the classpath.

The second one takes path that can start with a /. If it does, it starts at the root of the classpath. If not, it starts at the package of the class on which the method is called.

So getClass().getClassLoader().getResource("foo/bar.txt") is equivalent to getClass().getResource("/foo/bar.txt").

And, assuming getClass() returns a class that is in the package foo, getClass().getResource("bar.txt") is equivalent to getClass().getClassLoader().getResource("foo/bar.txt")

热点排行