Java批注:在变量初始化时,而不是赋值时? [英] Java annotations: at variable initialization, but not assignment?
问题描述
我一直在理解必须将注解确切放置在何处或可以放置注解的地方.
I've been having trouble understanding where exactly an annotation has to or can be placed.
具有此方法的类可以编译,但会发出未选中"警告:
The 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
}
此编译没有警告:
<B extends BitSet> void doStuff(LinkedList<B> list) {
B board = list.getFirst();
@SuppressWarnings("unchecked")
B cloneBoard = (B) board.clone();
}
这不会编译,但会将cloneBoard标记为错误:
This doesn't compile but marks 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
}
在有关注释的Sun教程中,我找不到为什么的答案: http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html .
In the Sun tutorial on annotations, I couldn't find an answer as 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 I understand it correctly: http://java.sun.com/docs/books/jls/third_edition/html/syntax.html#18.1
在我看来,这里的问题是注释可以专门用于变量,但只能在声明它们时使用.以后的任何作业都不会包含在注释中.这样对吗?除了抑制整个方法的未经检查的警告之外,还有一种更优雅的解决方案吗?
It seems to me that what's the problem here is that annotations can be specifically used for variables, but only when they are declared; any later assignment will not be covered by the annotation. Is this correct? Is there a more elegant solution than suppressing unchecked warnings for the whole method?
推荐答案
注释是声明的一部分;就像您不能在声明obj
的位置写Object obj
一样,也不能写final obj
以外的final obj
一样,也禁止写@Deprecated obj
.
An annotation is part of a declaration; just as you can't write Object obj
except at the point where obj
is declared, nor final obj
except as final Object obj
, so too is @Deprecated obj
forbidden.
至于优雅—理想情况下,无论如何,您的方法都不应太长且复杂,但是,如果您确实希望使用此批注标记特定的分配,则可以始终使用简单的包装器方法:
As for elegance — ideally your methods should not be very long and complicated, anyway, but if you do find that you'd like to mark a specific assignment with this annotation, you can always make use of a simple wrapper method:
@SuppressWarnings("unchecked")
private static <T extends ClassThatDeclaresCloneAsPublic> T cloneObj(T obj)
{ return (T) obj.clone(); }
(尽管在这种特定情况下,我想您可以编写cloneBoard = board.getClass().cast(board.clone());
并完全省去注释,如果您愿意的话.)
(Though in this specific case, I suppose you could write cloneBoard = board.getClass().cast(board.clone());
and dispense with the annotation altogether, if you wanted.)
这篇关于Java批注:在变量初始化时,而不是赋值时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!