What is the difference between getResourceAsStream with and without getClassLoader?

前端 未结 3 1821
迷失自我
迷失自我 2021-02-19 19:50

I\'d like to know the difference between the following two:

MyClass.class.getClassLoader().getResourceAsStream(\"path/to/my/properties\");

and

3条回答
  •  抹茶落季
    2021-02-19 20:18

    From the Class.getClassLoader() documentation:

    Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

    So getClassLoader() may return null if the class was loaded by the bootstrap class loader, hence the null check in the Class.getResourceAsStream implementation:

    public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }
    

    You'll also note the statement name = resolveName(name); which Mark Peters has explained in his answer.

提交回复
热议问题