Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

loading class with getResource() gives different results

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please notice that this is a simple case. Inside a webserver I have noticed much more weird situations; null appears in many more cases.

>Solution :

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 /.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading