Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
}
like image 599
A. Masson Avatar asked Jun 18 '13 15:06

A. Masson


3 Answers

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.

like image 66
Zavior Avatar answered Nov 18 '22 01:11

Zavior


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()

like image 29
Gyro Gearless Avatar answered Nov 18 '22 01:11

Gyro Gearless


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.

like image 3
Eric Jablow Avatar answered Nov 18 '22 01:11

Eric Jablow