henry henry - 1 year ago 135
Java Question

Sonar rule to catch raw collection types

I recently introduced sonar to a large legacy project, originally written in java 1.3.

We have been gradually migrating code using raw collections etc to use generics. It would be nice to track our progress in sonar, but there does not seem to be an out of the box rule to catch raw collection use.

Is there an existing solution, or will I need to create a custom rule in pmd/checkstyle?

Answer Source

I was looking for the same thing, because I would like our Sonar to catch this too:

List myList = new ArrayList();

The rule that Dennis S mentions does not apply, since it is meant to catch the following situation (according to http://coding.tocea.com/java/gc_unchecked_type_in_generic_call/)

StringBuilder myText = new StringBuilder();
List<String> myList = new ArrayList<String>();
boolean containsMyText = myList.contains(someText);

The code compiles because the collection.contains() method takes an Object parameter, even for typed collections. But it is an irrelevant check and will always return false, since the myText object has the wrong type and can never be added to the typed myListcollection.

From what I have seen, it seems you would have to build a custom rule.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download