January 19, 2012 Leave a comment
You think that java.lang.Class.getResource(String name) is the same as java.lang.ClassLoader.getResource(String name) ? Think again…
The javadoc for java.lang.Class.getResource(String name) states that:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
- Otherwise, the absolute name is of the following form: modified_package_name/name where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
Now compare this with the javadoc for java.lang.ClassLoader.getResource(String name) :
The name of a resource is a ‘/‘-separated path name that identifies the resource
Yes, this means that when using ClassLoader.getResource(String name), the path must NOT start with a ‘/’, and in the end, these 2 statements are similar:
this.getClass().getResource("/sub/file1.properties"); // note that there is no '/': this.getClass().getClassLoader().getResource("sub/file2.properties");