How to find out which methods cause warnings that use generics in Java

How to find out which methods cause warnings that use generics in Java


Generics can cause type-safe warnings to be reported by the compiler. This may occur if methods are using them improperly.


A Java development environment, such as a Java compiler (javac), runtime environment (jre), and source file editor, or Java integrated development environment (IDE).


Generics were introduced to Java in Java 1.5. Before this, objects such as collections, could not have type-safe member restrictions at compile-time. Since Java 1.5, generics have some backwards compatibility with old code, and can use non-type safe methods. These methods, however have been provided with compile-time type-safe checks. The compiler will issue a warning instead of an error. The methods that are not type-safe will not be reported by the compiler. They can be requested, however during compilation.

When you are ready to compile, run your compilation arguments after the java compiler (javac). You can include a specific argument to find out which method generated a warning. For instance, without the extra argument, you will see warning such as:

Note: uses unchecked or unsafe operations. 
Note: Recompile with -Xlint:unchecked for details.

If you use -Xlint:unchecked as an argument, you will get more verbose output about the warning. You can invoke the compiler with this argument as follows:

javac -Xlint:unchecked

This will generate something such as:

javac -Xlint:unchecked warning: [unchecked] unchecked call to add(E) as a memb 
er of the raw type List 
list.add(new String("aa")); 
where E is a type-variable: 
E extends Object declared in interface List 
1 warning

In the above output, the add() method is listed as having a warning on line 11. This method could be within a method that was from pre-Java 1.5 code. The older pre-generics code could still be used, but the compiler will still issue warnings if this case.

Even when only one type of member is added to a collection, if the collection is not type safe, such as in this method:

void methodName(List list){
String string = "aaa"; 

warnings will still be generated. The list declaration passed as a parameter in the method’s signature would not generate warnings if it had a generic type.