简体   繁体   中英

How does Class find resources?

The JavaDoc for Class#getResourceAsStream(String) reads:

Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.

So how does the following work:

class AppTest {
private static final Properties p = new Properties();    
    static {        
        try {
            p.load(AppTest.class.getResourceAsStream(("config.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
...
}

If config.properties sits in the same directory as AppTest.class:

pro/wulfgar/net/on/users/app/{AppTest.class,config.properties} 

shouldn't the class loader for AppTest.class be looking for it on the application classpath ( . in this case)? Therefore config.properties should be at the same level as the pro directory.

That is, unless I define the resource as pro/wulfgar/net/on/users/app/config.properties , I can't understand why the class loader can find the resource?

Check this out InputStream is = App.class.getResourceAsStream("test.properties");

There is a difference between Class.getResourceAsStream and ClassLoader.getResourceAsStream

The phrasing on the JavaDoc may be confusing you a bit. Class.getResourceAsStream(String) will resolve the resource in the package of the class reference (pro/wulfgar/net/on/users/app/config.properties). If you don't wish for it to resolve in this way, you add a "/" at the start of the resource name to indicate it is at the base level (pro/wulfgar/config.properties if you are following standard package convention).

This behavior is outlined in the second half of the JavaDoc. The quoted part of the JavaDoc explains that it delegates to the ClassLoader for that Class. Since each ClassLoader has a separate source of files (jars or file system), it distinguishes for that particular ClassLoader's set of resources.

The ClassLoader already knows the directory that AppTest.class is in due to the package name. It has no such information for the properties file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM