Bad Practice Sonar Flag: Using GetResource in XYZ May Be Insecure If Class Enhanced

Sonar points to this error in our Java project. Any suggestions for safe programming are welcome!

URL url = getClass().getResource("/myWonderfulResource.txt"); if (url == null) { throw new IllegalStateException("File not found: /myWonderfulResource.txt"); } 
+6
source share
3 answers

Make the class final so that it cannot be extended. A warning exists to prevent an extended class (potentially) trying to use non-existent resources.

+2
source

The only thing I can imagine why Sonar is spitting out this message is that the derived class can be loaded by another class loader, so then your text file cannot be found. I would just ignore this, make the class final as suggested, or use the .class literal instead of getClass()

+3
source

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.

+3
source

Source: https://habr.com/ru/post/947565/


All Articles