this.getClass().getClassLoader().getResource(“…”) and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package.
If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you’d done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can’t use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Leave a Comment