注释参数:显式vs.隐式String数组 [英] Annotation parameter: explicit vs. implicit String array

查看:153
本文介绍了注释参数:显式vs.隐式String数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

此错误的解释是什么?

推荐答案

如果使用数组常量传递它,则会出现语法错误.

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是基本类型或String,而V是常量表达式(第15.28节).
  • V不为空.
  • 如果T是Class或Class的调用,并且V是class文字(第15.8.2节).
  • 如果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.

ElementValueArrayInitializer与常规数组初始化程序(§10.6)相似,不同之处在于允许使用注释代替表达式.

An ElementValueArrayInitializer is similar to a normal array initializer (§10.6), except that annotations are permitted in place of expressions.

这篇关于注释参数:显式vs.隐式String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆