It seems @SuppressWarnings is not taken into account when compiling
To experiment with annotation @SuppressWarnings
, I wrote the following sample program:
public class Test {
public static void main(String[] args) {
@SuppressWarnings("unchecked")
Set set = new HashSet();
Integer obj = new Integer(100);
set.add(obj);
}
}
But even after this annotation I get the following output on the console:
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
If I move the annotation just before the main method declaration, then the warnings are suppressed. What's missing here?
Thank.
source to share
The compiler tells you Recompile with -Xlint:unchecked for details.
that this condition is met: if you annotated the declaration with @SuppressWarnings
, you also call the general method as a raw operation.
Test.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type Set
set.add(obj);
^
where E is a type-variable:
E extends Object declared in interface Set
If you move a method @SuppressWarnings
to a method main
as a whole, the warning disappears.
The JLS section doesn't@SuppressWarnings
say:
If a program declaration is annotated with the
@SuppressWarnings
[...] annotation , then the Java compiler should not report a warning [...] if that warning would have been generated as a result of the annotated declaration or any of its parts. (my bold font)
Your example code only suppresses the local variable declaration, not the method declaration.
Update
Oddly enough, even the message you received appears to be not technically a warning, but a note. Compiling with it -Werror
works fine. Using the option -Xlint
makes this warning.
source to share
Below is the program with no compile time warnings:
import java.util.*;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args){
Set set = new HashSet();
Integer obj = new Integer(100);
set.add(obj);
}
}
Remember this is just an annotation experiment. The ideal solution here is to use generics instead of raw types.
source to share