java - 注解参数: explicit vs.隐式String数组

标签 java arrays string annotations

为什么我的场景中的第二个测试在 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/

相关文章:

java - 记录格式错误的 Axis2 请求

java - 如何创建从商店提款和送货到商店的方法

c++ - Cuda "invalid argument"二维数组 - 元胞自动机

c# - 如何附加我的列表元素

java - 如何在 java 中查找字符串中的 EOF?

string - 批处理,比较两个文件并将差异写入另一个文件

java - Java GridLayout的第二个参数(a,b,x,y)?

java - 你能以编程方式获得类评论吗

arrays - 在一个巨大的二维数组中填充随机位置

objective-c - 指向 Objective-C 函数调用中的数组的指针