Search code examples
javaurlsonarqubeunsafegetresource

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");
}

Solution

  • 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.