为什么我的场景中的第二个测试在 SuppressWarnings
行上出现语法错误 注释属性 SuppressWarnings.value 的值必须是数组初始值设定项
?
public class AnnotationTest {
private static final String supUnused = "unused";
private static final String supDeprecation = "deprecation";
private static final String[] suppressArray = { "unused", "deprecation" };
public static void main(String[] args) {
// Test 1
@SuppressWarnings( { supUnused, supDeprecation } )
int a = new Date().getDay();
// Test 2
@SuppressWarnings(suppressArray) // syntax error
int b = new Date().getDay();
}
}
如果您将参数作为两个单个常量传递,则它可以工作。
如果您使用数组常量传递它,则会出现语法错误。
这个错误的解释是什么?
最佳答案
If you're passing it with an array constant, there is a syntax error.
注释参数必须是常量。
suppressArray
被声明为 final
,但这仅意味着您无法使用另一个数组引用重新分配 suppressArray
变量。您仍然可以更改 suppressArray
的内容,例如
suppressArray[0] = "someOtherString";
在第一个示例中,您使用内联数组初始值设定项。
@SuppressWarnings( { supUnused, supDeprecation } )
因此其他类无法获取对它的引用,因此无法更改数组的内容。
至少看看JLS 9.7.1给出了详细的解释。
注释参数是名称值对,其中 T
是名称值对的类型,而 V
是值:
- If T is a primitive type or String, and V is a constant expression (§15.28).
- V is not null.
- If T is Class, or an invocation of Class, and V is a class literal (§15.8.2).
- If T is an enum type, and V is an enum constant.
和
An ElementValueArrayInitializer is similar to a normal array initializer (§10.6), except that annotations are permitted in place of expressions.
关于java - 注解参数: explicit vs.隐式String数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21252475/