我一直无法理解必须或可以放置注释的确切位置。
具有此方法的类可以编译,但会给出警告“未检查”:
<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 标记为错误:
<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 .
语法定义对我也没有帮助,因为我不确定我是否理解正确:http://java.sun.com/docs/books/jls/third_edition/html/syntax.html#18.1
在我看来,这里的问题是注解可以专门用于变量,但只能在声明时使用;注释将不涵盖任何以后的分配。这样对吗?有没有比抑制整个方法的未检查警告更优雅的解决方案?
最佳答案
来自 Java Language Specification - Interfaces > Annotation
Annotations may be used as modifiers in any declaration, whether package, class, interface, field, method, parameter, constructor, or local variable..
它只能在声明中使用。
关于Java注解: at variable initialization,但不能赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425674/