Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between getResourceAsStream with and without getClassLoader?

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

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

and

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

Thank you.

like image 892
George Sun Avatar asked Sep 06 '12 04:09

George Sun


1 Answers

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.

like image 54
Paul Bellora Avatar answered Sep 18 '22 13:09

Paul Bellora