注释参数:显式与隐式字符串数组 [英] Annotation parameter: explicit vs. implicit String array
问题描述
为什么我的场景中的第二个测试有语法错误 The value for annotation attribute SuppressWarnings.value must be an array initializer
在 SuppressWarnings
行?
Why does the second Test in my scenario has the syntax error The value for annotation attribute SuppressWarnings.value must be an array initializer
on the SuppressWarnings
line?
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 the parameters as two single constants, it works.
If you're passing it with an array constant, there is a syntax error.
这个错误的解释是什么?
What is the explanation for this error?
推荐答案
如果您使用数组常量传递它,则会出现语法错误.
If you're passing it with an array constant, there is a syntax error.
注释参数必须是常量.
suppressArray
声明为 final
,但这仅意味着您不能使用另一个数组引用重新分配 suppressArray
变量.您仍然可以更改 suppressArray
的内容,例如
The suppressArray
is declared final
, but this only means that you can not reassign the suppressArray
variable with another array reference. You can still change the suppressArray
's content, e.g.
suppressArray[0] = "someOtherString";
在您的第一个示例中,您使用内联数组初始值设定项.
In your first example you use an array initializer inline.
@SuppressWarnings( { supUnused, supDeprecation } )
因此没有其他类可以获得对它的引用,因此不能改变数组的内容.
Therefore no other class can obtain a reference to it and thus can not change the array's content.
至少看看 JLS 9.7.1给出了详细的解释.
At least a look at the JLS 9.7.1 gives a detailed explanation.
注解参数是名称值对,其中 T
是名称值对的类型,而 V
是值:
The annotation arguements are name value pairs where T
is the type of the name value pair while V
is the value:
- 如果 T 是原始类型或字符串,并且 V 是常量表达式(第 15.28 节).
- V 不为空.
- 如果 T 是类,或类的调用,并且 V 是类文字(第 15.8.2 节).
- 如果 T 是枚举类型,而 V 是枚举常量.
和
ElementValueArrayInitializer 类似于普通数组初始值设定项(第 10.6 节),但允许使用注释代替表达式.
An ElementValueArrayInitializer is similar to a normal array initializer (§10.6), except that annotations are permitted in place of expressions.
这篇关于注释参数:显式与隐式字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!