Standard Analyses

SemmleCode Professional comes with a wide range of pre-packaged analyses, from architectural properties and metrics, to statement-level checks for likely bugs and violations of best practice.


Unsafe Use of getResource

This query finds expressions of the form

    this.getClass().getResource()

This is not a safe way to retrieve resources. Assume such an expression occurs in a method m of a class X. If Y is a subclass of X, then this.getClass() may refer to either the class object of X or the class object of Y, depending on the dynamic type of the object m is invoked upon.

How to Interpret the Query Results

The query flags all such expressions and provides a list of all detected occurrences in the results view.

How to Address the Query Results

Use X.class.getResource() instead.

Source Code
import default

// Find public classes where there is a call to  this.getClass().getResource(String s) 
// or this.getClass().getResourceAsStream(String s)

/** Access to a method in this object */
class MethodAccessInThis extends MethodAccess {
  MethodAccessInThis() {
       not this.hasQualifier()
    or this.getQualifier() instanceof ThisAccess
  }
}

from Class c, MethodAccess getResource, MethodAccessInThis getClass
where getResource.getNumArgument() = 1 and
      (   getResource.getMethod().hasName("getResource")
       or getResource.getMethod().hasName("getResourceAsStream")) and
      getResource.getQualifier() = getClass and
      getClass.getNumArgument() = 0 and
      getClass.getMethod().hasName("getClass") and
      getResource.getEnclosingCallable().getDeclaringType() = c and
      c.hasModifier("public")
select getResource, "Usage of GetResource may be unsafe if class is extended"
References

JavaWorld article Got resources?