有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java注释参数:显式与隐式字符串数组

为什么我的场景中的第二个测试在SuppressWarnings行上有语法错误The value for annotation attribute SuppressWarnings.value must be an array initializer

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();
    }
}

如果您将参数作为两个单一常量传递,则它会起作用
如果使用数组常量传递,则会出现语法错误

这个错误的原因是什么


共 (1) 个答案

  1. # 1 楼答案

    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.