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.


Impossible Array Cast

This query finds downcasts on array creation expressions that are guaranteed to fail at runtime.

An object a with dynamic type A[] cannot be cast to B[], where B is a subtype of A, even if all the elements of a can be cast to B. For example, the following code throws a class cast exception at runtime:

    String[] strs = (String[])new Object[]{ "hello", "world" };
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

Change the array creation expression to construct an array object of the right type.

Source Code
import default

from CastExpr ce, RefType target, RefType source
where ce.getExpr() instanceof ArrayCreationExpr and
      target = ((Array)ce.getType()).getElementType() and
      source = ((Array)ce.getExpr().getType()).getElementType() and
      target.hasSupertype+(source) 
select ce, "Impossible downcast on array."
References