eg:
TemplateCode.class.getClass().getClassLoader().getResource("foo/bar.txt")
TemplateCode.class.getClassLoader().getResource("foo/bar.txt")的区别
第二句话实际上还是调用的第一句,
区别在于第一句话不能以/开始,并总是从classpath的根目录开始查找,
第二句如果以/开始,则从根目录开始查找,如果开始不加/则从当前类所在的路径开始查找
[b][color=red]验证通过[/color][/b]
参考原文
http://stackoverflow.com/questions/14739550/what-is-the-difference-between-getclass-getclassloader-getresource-and-get
[quote]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")[/quote]
TemplateCode.class.getClass().getClassLoader().getResource("foo/bar.txt")
TemplateCode.class.getClassLoader().getResource("foo/bar.txt")的区别
第二句话实际上还是调用的第一句,
区别在于第一句话不能以/开始,并总是从classpath的根目录开始查找,
第二句如果以/开始,则从根目录开始查找,如果开始不加/则从当前类所在的路径开始查找
[b][color=red]验证通过[/color][/b]
参考原文
http://stackoverflow.com/questions/14739550/what-is-the-difference-between-getclass-getclassloader-getresource-and-get
[quote]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")[/quote]