The sonar error message does not seem to make much sense, because the resource starts with a slash, and therefore is considered at the root of the class path. However, Sonar may not check what is in the resource string, and then he will assume that the path may be a relative path.
Imagine what would happen if you wrote a line without a slash:
URL url = getClass().getResource("myWonderfulResource.txt");
In the current package, the URL would point to myWonderfulResource.txt . Now suppose you extended the class in another package.
package com.example; public class Wonderous {...} package com.example.awesome; public class Awesome extends Wonderous {...}
When an Awesome instance tries to get a wonderful text file, it looks at the class path in com / example / awesome. But the Wonderful resource is in com/example . Awesome will not find it.
By the way, this error report comes from FindBugs, and the documentation for this specific error:
UI: using GetResource may be unsafe if the class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)
Call this.getClass (). getResource (...) may produce results other than expected if this class is extended by a class in another package.
source share