前者会调用后者,只不过调用前会把字符串进行处理。
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResource(name);
}
return cl.getResource(name);
}
rivate String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class<?> c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/')
+"/"+name; // 非"/"开头会附上包名路径
}
} else {
name = name.substring(1); // "/"开头的会去掉"/"
}
return name;
}
System.out.println(Application.class.getResource(""));// 非"/"开头的话,会加上包名路径后再搜索
System.out.println(Application.class.getResource("/"));
System.out.println(Application.class.getClassLoader().getResource(""));
System.out.println(Application.class.getClassLoader().getResource("/"));
输出
file:/D:/spring/mybatis-redis-annotation/target/classes/org/spring/springboot/
file:/D:/spring/mybatis-redis-annotation/target/classes/
file:/D:/spring/mybatis-redis-annotation/target/classes/
null
后者在遇到"/"开头的字符串时返回null
。
网友评论