无法声明注释数组

Unable to declare array of annotations

我有两个方法的注释

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 hereannoArray.

的位置

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

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

  1. 您可以为 AnnoationB 值创建常量。
  2. 如果AnnotationB只包含一个String,而你需要多个,你可以将AnnotationA的值成员定义为一个String[](也可以在这里定义常量)