ITeye博客

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

roc08 · 2013-11-21 16:59 · java · 编程语言 · Markdown

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")

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。