【问题标题】:Unable to declare array of annotations无法声明注释数组
【发布时间】:2017-02-07 04:38:03
【问题描述】:

我在两个方法上有注释

public class Question {

    @AnnotationA(value = { @AnnotationB(message = "One"), @AnnotationB(message = "Two") })
    public int methodOne() {
        return 1;
    }

    @AnnotationA(value = { @AnnotationB(message = "One"), @AnnotationB(message = "Two") })
    public int methodTwo() {
        return 2;
    }
}

我希望能够写作

public class Question {

    @AnnotationA(value = annoArray)
    public int methodOne() {
        return 1;
    }

    @AnnotationA(value = annoArray)
    public int methodTwo() {
        return 2;
    }

    public AnnotationB[] annoArray = { @AnnotationB(message = "One"), @AnnotationB(message = "Two") }
}

但 IntelliJ 告知我 Annotations are not allowed here 位于 annoArray 的位置。

有没有其他方法可以做到这一点?

【问题讨论】:

    标签: java reflection annotations metaprogramming swagger


    【解决方案1】:

    这是不可能的,因为注解必须是编译时常量。但是,您至少有两种可能性:

    1. 您可以为 AnnoationB 值创建常量。
    2. 如果 AnnotationB 只包含一个字符串并且您需要多个字符串,您可以将 AnnotationA 的值成员定义为 String[](您也可以在此处定义常量)

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多