Java annotations: with initialization variable but not in assignment?

I am having trouble understanding where exactly or the annotation can be placed.

A class with this method compiles, but gives a warning "unchecked":

<B extends BitSet> void doStuff(LinkedList<B> list) { B board = list.getFirst(); B cloneBoard; cloneBoard = (B) board.clone(); //unchecked } 

This compiles without warning:

 <B extends BitSet> void doStuff(LinkedList<B> list) { B board = list.getFirst(); @SuppressWarnings("unchecked") B cloneBoard = (B) board.clone(); } 

This does not compile, but notes cloneBoard with an error:

 <B extends BitSet> void doStuff(LinkedList<B> list) { B board = list.getFirst(); B cloneBoard; @SuppressWarnings("unchecked") cloneBoard = (B) board.clone(); // cloneBoard cannot be resolved to a type; // VariableDeclaratorID expected } 

In the Sun annotation tutorial, I did not find an answer to why this is: http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html .

The grammar definition didn’t help me either, since I’m not quite sure that I understand correctly: http://java.sun.com/docs/books/jls/third_edition/html/syntax.html#18.1

It seems to me that the problem is that annotations can be specifically used for variables, but only when they are declared; annotations will not be covered by any subsequent assignment. It's right? Is there a more elegant solution than suppressing unverified warnings for the whole method?

+4
source share
3 answers

An annotation is part of the declaration; just as you cannot write Object obj , except at the point where obj declared, not final obj , except final Object obj , @Deprecated obj also forbidden.

Regarding elegance; Ideally, your methods should not be very long and complicated, anyway, but if you find that you want to mark a specific task with this annotation, you can always use a simple wrapping method:

 @SuppressWarnings("unchecked") private static <T extends ClassThatDeclaresCloneAsPublic> T cloneObj(T obj) { return (T) obj.clone(); } 

(Although in this particular case, I suppose, you could write cloneBoard = board.getClass().cast(board.clone()); and generally discard the annotation if you wanted to.)

+2
source

From Java Language Specification - Interfaces> Annotations

Annotations can be used as modifiers in any declaration, be it a package, class, interface, field, method, parameter, constructor or local variable.

It can only be used in ads.

+3
source

Annotations are part of the declaration (others have already answered this part).

However, to answer the second part of your question: I never had a problem marking the whole method with this annotation when the method is just as short. I personally prefer annotations at the method / class level, rather than inside the methods, because I think they just distract the reader.

+1
source

Source: https://habr.com/ru/post/1385272/


All Articles