I cannot understand how Class.getResource()
and ClassLoader.getResource()
methods works.
I wrote this:
public class Prova {
public static void main(String[] args) {
System.out.println(Prova.class.getResource("/java/lang/String.class"));
System.out.println(String.class.getResource("/java/lang/String.class"));
System.out.println(Prova.class.getClassLoader().getResource("/java/lang/String.class"));
}
}
Here is the output:
jar:file:/C:/Program%20Files/Java/jre1.8.0_301/lib/rt.jar!/java/lang/String.class
jar:file:/C:/Program%20Files/Java/jre1.8.0_301/lib/rt.jar!/java/lang/String.class
null
So, why is the third null? I would expect to get the same result as before.
Please notice that this is a simple case. Inside a webserver I have noticed much more weird situations; null
appears in many more cases.
Class.getResource expects a path relative to its package subdirectory.
Absolute (=from the top directory) paths start with a /
.
ClassLoader only knows absolute paths which are not allowed to start with a /
.