您的位置:首页 > 编程语言 > Java开发

java-getClass().getResource()与getClassLoader().getResource()

2016-01-11 18:41 537 查看

getClass().getResource("path")

当path以/开头,如/a/b/c.properties时,查找的路径为: classpath路径+path。
当path不以/开头时,如c.properties,查找的路径为:当前调用类的路径+path。

如:



则,代码为:
InputStream inputStream3= getClass().getResource("/com.phl.amodel/a.properties").openStream();

查找路径计算: classpath路径+path ,即:classpath+/com.phl.amodel/a.properties


getClassLoader().getResource("path")

只在当前类路径下寻找: classpath+path
如a.properties放在



代码:

InputStream inputStream2= getClass().getClassLoader().getResource("com.phl.amodel/a.properties").openStream();

(不能用/开头)


查找路径计算:path=com.phl.amodel/a.properties
则查找路径为 classpath+com.phl.amodel/a.properties

当多个jar中都含有要查找的资源时,应该从哪个jar中查找

根据jar包的先后顺序加载满足path的资源
那jar包的顺序是怎么的呢?
如果是maven工程,则以在pom中配置的先后为准,如有下面配置文件:



则先在useresource工程中根据path路径查找,然后在zmodel,amodel,test1,designmodel中查找。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: