Omkar Shetkar
Omkar Shetkar

Reputation: 3636

Seems @SuppressWarnings is not considered during compilation

To experiment with @SuppressWarnings annotation I have written 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 following output on 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 warnings are suppressed. What is missing here?

Thanks.

Upvotes: 3

Views: 343

Answers (2)

Omkar Shetkar
Omkar Shetkar

Reputation: 3636

Following will be 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 for experiment with annotation. Here ideal solution is to use generics instead of raw types.

Upvotes: 0

The compiler tells you to Recompile with -Xlint:unchecked for details. Doing so provides the context: while you annotated the declaration with @SuppressWarnings, you are also calling a generic 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 the @SuppressWarnings to the main method as a whole, the warning goes away.

The JLS section on @SuppressWarnings says:

If a program declaration is annotated with the annotation @SuppressWarnings[...] then a Java compiler must not report any warning [...] if that warning would have been generated as a result of the annotated declaration or any of its parts. (my bold)

Your example code only suppresses the local-variable declaration, not the method declaration.

Update

Oddly enough, even the message you got apparently isn't technically a warning but a note. Compiling with -Werror works just fine. Using an -Xlint option makes it a warning.

Upvotes: 5

Related Questions