views:

161

answers:

3

Try to write:

List<Object> list;
@SuppressWarnings("unchecked")
list = (List<Object>) new Object();

It will fail on the 3rd line, on the word list, with the following:

list cannot be resolved to a type

I understand that it is related to how annotations work. Anybody knows the reasoning behind this?

EDIT: thanks for the fast answer. I knew it'd work if the assignment was made also a declaration, anyway.

+2  A: 

You must put the annotation on the declaration, not just the assignment. This compiles:

@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) new Object();

See the Javadocs for SuppressWarnings, which lists its targets as

@Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})

And if you look up LOCAL_VARIABLE, it says:

Local variable declaration

(There is no target for arbitrary statements, so no annotation could possibly go there and still allow it to compile.)

Michael Myers
JDK7 is likely to add annotations on generic arguments. Can't remember the JSR number off hand.
Tom Hawtin - tackline
A: 

The annotation needs to be placed on a declaration, not an expression

@SuppressWarnings("unchecked") List<Object> lst 
   = (List<Object>)getProperty("mylist");
list = lst;

If list is declared elsewhere you could just declare a new local variable with the suppress annotation and perform the assignment after that.

kd304
+1  A: 

From Sun's Annotation Tutorial:

Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.

The end phrase "and other program elements" is disappointingly vague, but according to The Java Programming Language - Annotations:

Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants.

which makes it clear that Annotations can only be applied to declarations.

Bill the Lizard