The error message from Sonar doesn't seem to make much sense because the resource begins with a slash, and so is looked up at the root of the class path. However, Sonar might not check what is in the resource string, and it will then assume the path might be a relative path..
Imagine what would happen had you written a string without a slash:
URL url = getClass().getResource("myWonderfulResource.txt");
The url would have been pointing to myWonderfulResource.txt
in the current package. Now, suppose you extended the class in a different package.
package com.example;
public class Wonderous {...}
package com.example.awesome;
public class Awesome extends Wonderous {...}
When an instance of Awesome
tries to get the wonderful text file, it looks it up on the class path in com/example/awesome. But Wonderful
's resource is in com/example
. Awesome
won't find it.
Incidentally, this error report comes from FindBugs, and the documentation for this particular bug is:
UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)
Calling this.getClass().getResource(...) could give results other than expected if this class is extended by a class in another package.