Some clever new PMD rules - watch out for Collection.toArray()!

29 Nov 2005

Fabio Insaccanebbia contributed some nifty new PMD rules in the past day or two. The first one catches code like this:

void bar() {
 Collection c=new ArrayList();
 c.add(Integer obj=new Integer(1));
 Integer[] a=(Integer [])c.toArray(); // oops!  
}

See the problem? Collection.toArray() will return an array of Object types, not of Integer types. So this code would result in a runtime ClassCastException. Fabio's new rule - ClassCastExceptionWithToArray in the basic ruleset - will catch this.

Also, using the BigDecimal constructor that takes a double is a bad idea - even the Javadoc for it says "Note: the results of this constructor can be somewhat unpredictable." Bleah. So he wrote another rule - AvoidDecimalLiteralsInBigDecimalConstructor in the basic ruleset - to catch those as well.

Great stuff, Fabio, thanks very much!