Sonar flag "Bad practice": Usage of GetResource in XYZ may be unsafe if class is extended
Asked Answered
P

3

6

Sonar is indicating this error in our Java project. Any suggestion for safe programming is welcome!

URL url = getClass().getResource("/myWonderfulResource.txt");
if (url == null) {
  throw new IllegalStateException("File not found: /myWonderfulResource.txt");
}
Peursem answered 18/6, 2013 at 15:14 Comment(0)
P
3

Make the class final so it can not be extended. The warning is there to prevent the extended class (potentially) trying to use inexistent resources.

Paulin answered 18/6, 2013 at 15:15 Comment(1)
Flagged this as accepted answer because that solved the problem in our particular situation. However if you do not want/can set your class as final read more below...Peursem
Y
3

The only thing i can imagine why Sonar spits out this message is because a derived class may be loaded by a different classloader, so your textfile might not be found then. I'd just ignore this, make the class final as suggested, or use a .class literal instead of getClass()

Yoshikoyoshio answered 18/6, 2013 at 15:22 Comment(0)
D
3

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.

Dudek answered 18/6, 2013 at 15:23 Comment(2)
Good point, which renders my advice on using a .class literal somewhat useless. Ignoring still works if we keep the leading "/" :-)Yoshikoyoshio
if you used Wonderous.class, Sonar might accept it. After all, subclasses would still use the same class and the same package in the class path. If you use the absolute resource path, it would be safe, but Sonar probably doesn't check. I'll edit my answer to make it clearer.Dudek

© 2022 - 2024 — McMap. All rights reserved.