Generic code is free to be used with raw types, preserving the compatibility of non-generic legacy code and newer generic code. However, using raw types with generic code will cause the java compiler to issue "unchecked" warnings. When generic and non-generic code are used correctly together these warnings are no threat, but the same warnings are issued when unsafe operations are performed. If generic and non-generic code must be used together these warnings should not be simply ignored.
Noncompliant Code Example
This code ordinarily produces an unchecked warning because the raw type of the List.add method is being used instead of the parameterized type. To make this compile cleanly, the SuppressWarnings annotation is used.
import java.util.*; public class Test { @SuppressWarnings("unchecked") public static void addToList(List list, Object obj) { list.add(obj); // "unchecked" warning } public static <T> void printOne(T type) { if (!(type instanceof Integer || type instanceof Double)) System.out.println("Cannot print in the supplied type"); List<T> list = new ArrayList<T> (); addToList(list, 1); System.out.println(list.get(0)); } public static void main(String[] args) { double d = 1; int i = 1; System.out.println(d); Test.printOne(d); System.out.println(i); Test.printOne(i); } }
This code will produce this output
1.0 1 1 1
Compliant Solution
TODO
TODO
Risk Assessment
TODO
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC10-J |
— |
— |
— |
--- |
--- |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
TODO