【问题标题】:Annotation parameter: explicit vs. implicit String array注释参数:显式与隐式字符串数组
【发布时间】:2014-01-21 08:10:25
【问题描述】:

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

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

这个错误的解释是什么?

【问题讨论】:

  • @RafaEl:感谢您提供文档链接!关键是,我已经知道,你必须使用 SupressWarnings ;)
  • 是的,我当然知道你知道这一点。但是..好吧,我不知道为什么我给你链接:D
  • @Downvoter:请解释一下!

标签: java arrays string annotations


【解决方案1】:

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

注解参数必须是常量。

suppressArray 被声明为final,但这仅意味着您不能用另一个数组引用重新分配suppressArray 变量。您仍然可以更改suppressArray 的内容,例如

suppressArray[0] = "someOtherString";

在您的第一个示例中,您使用内联数组初始值设定项。

@SuppressWarnings( { supUnused, supDeprecation } )

因此没有其他类可以获取对它的引用,因此不能更改数组的内容。

至少看看JLS 9.7.1 给出了详细的解释。

注释参数是名称值对,其中T 是名称值对的类型,而V 是值:

  • 如果 T 是原始类型或字符串,而 V 是常量表达式(第 15.28 节)。
  • V 不为空。
  • 如果 T 是 Class,或 Class 的调用,而 V 是类文字(第 15.8.2 节)。
  • 如果 T 是枚举类型,而 V 是枚举常量。

ElementValueArrayInitializer 类似于普通的数组初始值设定项(第 10.6 节),不同之处在于允许使用注释代替表达式。

【讨论】:

  • 伟大而合理的答案!我正在努力解决must be an array initializer。因为,它实际上是一个数组初始值设定项,但方式不同......你的解释显示了,为什么不能通过引用传递一个数组。谢谢!
猜你喜欢
  • 2017-11-14
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2013-02-10
相关资源
最近更新 更多