resources.report.rules.pmd.ClassCastExceptionWithToArray.html Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sanity4j Show documentation
Show all versions of sanity4j Show documentation
Sanity4J was created to simplify running multiple static code
analysis tools on the Java projects. It provides a single entry
point to run all the selected tools and produce a consolidated
report, which presents all findings in an easily accessible
manner.
ClassCastExceptionWithToArray
ClassCastExceptionWithToArray
if you need to get an array of a class from your Collection,
you should pass an array of the desidered class
as the parameter of the toArray method. Otherwise you will get a
ClassCastException.
This rule is defined by the following XPath expression:
//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image !=
"Object"]]//PrimaryExpression
[
PrimaryPrefix/Name[ends-with(@Image, '.toArray')]
and
PrimarySuffix/Arguments[count(*) = 0]
and
count(PrimarySuffix) = 1
]
Example:
import java.util.ArrayList;
import java.util.Collection;
public class Test {
public static void main(String[] args) {
Collection c=new ArrayList();
Integer obj=new Integer(1);
c.add(obj);
// this would trigger the rule (and throw a ClassCastException
if executed)
Integer[] a=(Integer [])c.toArray();
// this wouldn't trigger the rule
Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);
}
}