ClassLoader

获取classpath下的资源文件

先调用当前线程的context加载器的getResourceAsStream方法去获取

没找到,在调用当前传入类的类加载器的getResourceAsStream方法获取

    public static InputStream getResourceAsStream(Class clazz, String name) {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
        if (in == null) {
            in = clazz.getResourceAsStream(name);
        }
        return in;
    }

递归获取加载某个类的类加载器链条信息

    private static String showClassLoaderHierarchy(ClassLoader cl, String delim, String tabText, int indent) {
        if (cl == null) {
            String s = "null classloader " + delim;
            ClassLoader ctxcl = Thread.currentThread().getContextClassLoader();
            s += "Context class loader=" + ctxcl + " hc=" + ctxcl.hashCode();
            return s;
        }
        StringBuilder s = new StringBuilder(); //"ClassLoader: ";
        for (int i = 0; i < indent; i++) {
            s.append(tabText);
        }
        s.append(cl).append(" hc=").append(cl.hashCode()).append(delim);
        ClassLoader parent = cl.getParent();
        return s.toString() + showClassLoaderHierarchy(parent, delim, tabText, indent + 1);
    }

 

posted @ 2019-03-08 23:14 风一样的码农 阅读(...) 评论(...) 编辑 收藏