[Java] Unchecked generic type operation

java

(Werner Thumann) #1

Description
Casts involving generics are not checked at runtime because generic type information is not present in the bytecode. Hence such casts will provoke runtime exceptions only when the generic type is used. The snippet below demonstrates this problem. Such casts usually indicate a faulty design using of generics.

Type
Code Smell

Snippet

public class UncheckedGenericTypeOperation {

	public static void main(String[] args) {
		List<String> list = (List<String>) getAttributes(); // Noncompliant
		String s = list.get(0); // exception
	}

	private static List<?> getAttributes() {
		List<Integer> result = new ArrayList<>();
		result.add(0);
		return result;
	}
	
}

Note
Also covered by Eclipse JDT.


(Alexandre Gigleux) #3

Hello Werner,

The specification was already there on our side waiting someone like you to push for it: https://jira.sonarsource.com/browse/RSPEC-1944

Here is the related implementation ticket: https://jira.sonarsource.com/browse/SONARJAVA-723

Regards