美文网首页
class.getResource和classLoader.ge

class.getResource和classLoader.ge

作者: 不存在的里皮 | 来源:发表于2019-04-19 00:34 被阅读0次

前者会调用后者,只不过调用前会把字符串进行处理。

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

相关文章

网友评论

      本文标题:class.getResource和classLoader.ge

      本文链接:https://www.haomeiwen.com/subject/lahfgqtx.html