lucian.marcuta
lucian.marcuta

Reputation: 1260

Using @SuppressWarnings within method generates compile error

I have the following code block:

     final Map<String, Double> map;
            if (cond) {
                int currency = 44;
                @SuppressWarnings("unchecked")
                map = (Map<String, Double>)objectA.get();
            }else {
                map= ....}

get() method of objectA returns a raw HashMap(I know that would be nice to use generics there and my problem would be solved, but i cannot change the code from that class). If I remove @SuppressWarnings("unchecked") line, obviously I get an TypeSafety warning. But when I add supress warning in line that is right bellow assignment, I get the following error :

map cannot be resoved to a type!

Could someone explain me why?

Upvotes: 1

Views: 1400

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

In Java, a Local Variable Declaration Statement can be annotated. Other types of statements can not.

Your code shows an expression statement (an assignment expression):

@SuppressWarnings("unchecked")
map = (Map<String, Double>)objectA.get();

This cannot be annotated. You probably started with a Local Variable Declaration Statement like below and then moved the type Map<String, Double> outside the if statement:

@SuppressWarnings("unchecked")
Map<String, Double> map = (Map<String, Double>)objectA.get();

The Java parser will actually expect a Local Variable Declaration Statement, if it sees an annotation within a method (or a type declaration, but let's ignore that now). Such a statement always starts with a type, and that's what the error is telling you: map is not a valid type.

(Note that if map were a valid type, it would then complain that you didn't specify an identifier before the =.)

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

The compiler thinks that @SuppressWarnings("unchecked") is an expression and there's no terminal operator ;. However, if you add it, the expression is invalid.

You have to annotate the method or use the annotation before the variable definition:

@SuppressWarnings("unchecked") 
public void method() {
    @SuppressWarnings("unchecked") final Map<String, Double> map;
    if (cond) {
        int currency = 44;
        map = (Map<String, Double>)objectA.get();
    }
}

Note that the javadoc suggests that:

As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective.

Upvotes: 6

Related Questions