88

我无法使用从常量中获取的枚举作为注释中的参数。我收到此编译错误:“注释属性 [attribute] 的值必须是枚举常量表达式”。

这是 Enum 代码的简化版本:

public enum MyEnum {
    APPLE, ORANGE
}

对于注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface MyAnnotation {
    String theString();

    int theInt();

    MyEnum theEnum();
}

和班级:

public class Sample {
    public static final String STRING_CONSTANT = "hello";
    public static final int INT_CONSTANT = 1;
    public static final MyEnum MYENUM_CONSTANT = MyEnum.APPLE;

    @MyAnnotation(theEnum = MyEnum.APPLE, theInt = 1, theString = "hello")
    public void methodA() {

    }

    @MyAnnotation(theEnum = MYENUM_CONSTANT, theInt = INT_CONSTANT, theString = STRING_CONSTANT)
    public void methodB() {

    }

}

该错误仅出现在方法 B 上的“theEnum = MYENUM_CONSTANT”中。编译器可以使用 String 和 int 常量,但 Enum 常量不行,即使它与方法 A 上的值完全相同。在我看来这是编译器中缺少的功能,因为这三个显然都是常量。没有方法调用,没有奇怪的类使用等。

我想要实现的是:

  • 在注释和后面的代码中使用 MYENUM_CONSTANT。
  • 保持打字安全。

任何实现这些目标的方法都可以。

编辑:

谢谢大家。正如你所说,这是不可能的。JLS 应该更新。这次我决定忘记注释中的枚举,并使用常规的 int 常量。只要 int 是从命名常量分配的,值就是有界的,并且它是“某种”类型安全的。

它看起来像这样:

public interface MyEnumSimulation {
    public static final int APPLE = 0;
    public static final int ORANGE = 1;
}
...
public static final int MYENUMSIMUL_CONSTANT = MyEnumSimulation.APPLE;
...
@MyAnnotation(theEnumSimulation = MYENUMSIMUL_CONSTANT, theInt = INT_CONSTANT, theString = STRING_CONSTANT)
public void methodB() {
...

而且我可以在代码的其他任何地方使用 MYENUMSIMUL_CONSTANT。

4

6 回答 6

139

“计算机科学中的所有问题都可以通过另一个层次的间接性来解决”——大卫·惠勒

这里是:

枚举类:

public enum Gender {
    MALE(Constants.MALE_VALUE), FEMALE(Constants.FEMALE_VALUE);

    Gender(String genderString) {
    }

    public static class Constants {
        public static final String MALE_VALUE = "MALE";
        public static final String FEMALE_VALUE = "FEMALE";
    }
}

人物类:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import static com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import static com.fasterxml.jackson.annotation.JsonTypeInfo.Id;

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = Person.GENDER)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Woman.class, name = Gender.Constants.FEMALE_VALUE),
    @JsonSubTypes.Type(value = Man.class, name = Gender.Constants.MALE_VALUE)
})
public abstract class Person {
...
}
于 2013-05-05T12:04:46.347 回答
45

我认为投票最多的答案是不完整的,因为它根本不能保证枚举值与基础常String量值相结合。使用该解决方案,应该将这两个类解耦。

相反,我宁愿建议通过强制枚举名称和常量值之间的相关性来加强该答案中显示的耦合,如下所示:

public enum Gender {
    MALE(Constants.MALE_VALUE), FEMALE(Constants.FEMALE_VALUE);

    Gender(String genderString) {
      if(!genderString.equals(this.name()))
        throw new IllegalArgumentException();
    }

    public static class Constants {
        public static final String MALE_VALUE = "MALE";
        public static final String FEMALE_VALUE = "FEMALE";
    }
}

正如@GhostCat在评论中指出的那样,必须进行适当的单元测试以确保耦合。

于 2017-02-03T17:37:57.047 回答
25

它似乎在JLS #9.7.1中定义:

[...] V 的类型与 T 的赋值兼容(第 5.2 节),此外:

  • [...]
  • 如果 T 是枚举类型,而 V 是枚举常量。

枚举常量被定义为实际的枚举常量(JLS #8.9.1),而不是指向该常量的变量。

底线:如果你想使用枚举作为注释的参数,你需要给它一个明确的MyEnum.XXXX值。如果要使用变量,则需要选择另一种类型(不是枚举)。

一种可能的解决方法是使用 a Stringorint然后您可以映射到您的枚举 - 您将失去类型安全性,但可以在运行时轻松发现错误(=在测试期间)。

于 2012-11-06T15:11:07.613 回答
7

控制规则似乎是“如果 T 是枚举类型,而 V 是枚举常量。”,9.7.1。普通注释。从文本中可以看出,JLS 的目标是对注释中的表达式进行极其简单的评估。枚举常量特别是枚举声明中使用的标识符。

即使在其他情况下,使用枚举常量初始化的 final 似乎也不是常量表达式。4.12.4。final 变量说“一个原始类型或字符串类型的变量,它是 final 并使用编译时常量表达式(第 15.28 节)初始化,称为常量变量。”,但不包括使用枚举常量。

我还测试了一个简单的案例,在这个案例中,表达式是否是常量表达式很重要——一个围绕对未分配变量的赋值的 if。变量没有被赋值。测试最终 int 的相同代码的替代版本确实使变量明确分配:

  public class Bad {

    public static final MyEnum x = MyEnum.AAA;
    public static final int z = 3;
    public static void main(String[] args) {
      int y;
      if(x == MyEnum.AAA) {
        y = 3;
      }
  //    if(z == 3) {
  //      y = 3;
  //    }
      System.out.println(y);
    }

    enum MyEnum {
      AAA, BBB, CCC
    }
  }
于 2012-11-06T15:10:04.283 回答
3

我引用问题的最后一行

任何实现这些目标的方法都可以。

所以我尝试了这个

  1. 在注解中添加了一个 enumType 参数作为占位符

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    public @interface MyAnnotation {
    
        String theString();
        int theInt();
        MyAnnotationEnum theEnum() default MyAnnotationEnum.APPLE;
        int theEnumType() default 1;
    }
    
  2. 在实现中添加了一个 getType 方法

    public enum MyAnnotationEnum {
        APPLE(1), ORANGE(2);
        public final int type;
    
        private MyAnnotationEnum(int type) {
            this.type = type;
        }
    
        public final int getType() {
            return type;
        }
    
        public static MyAnnotationEnum getType(int type) {
            if (type == APPLE.getType()) {
                return APPLE;
            } else if (type == ORANGE.getType()) {
                return ORANGE;
            }
            return APPLE;
        }
    }
    
  3. 进行了更改以使用 int 常量而不是枚举

    public class MySample {
        public static final String STRING_CONSTANT = "hello";
        public static final int INT_CONSTANT = 1;
        public static final int MYENUM_TYPE = 1;//MyAnnotationEnum.APPLE.type;
        public static final MyAnnotationEnum MYENUM_CONSTANT = MyAnnotationEnum.getType(MYENUM_TYPE);
    
        @MyAnnotation(theEnum = MyAnnotationEnum.APPLE, theInt = 1, theString = "hello")
        public void methodA() {
        }
    
        @MyAnnotation(theEnumType = MYENUM_TYPE, theInt = INT_CONSTANT, theString = STRING_CONSTANT)
        public void methodB() {
        }
    
    }
    

我从 MYENUM_TYPE int 派生了 MYENUM 常量,因此如果更改 MYENUM,只需将 int 值更改为相应的枚举类型值。

它不是最优雅的解决方案,但我给出它是因为问题的最后一行。

任何实现这些目标的方法都可以。

只是一个旁注,如果你尝试使用

public static final int MYENUM_TYPE = MyAnnotationEnum.APPLE.type;

编译器在注释处说- MyAnnotation.theEnumType 必须是一个常量

于 2012-11-08T11:35:25.053 回答
-1

我的解决方案是

public enum MyEnum {

    FOO,
    BAR;

    // element value must be a constant expression
    // so we needs this hack in order to use enums as
    // annotation values
    public static final String _FOO = FOO.name();
    public static final String _BAR = BAR.name();
}

我认为这是最干净的方法。这满足了几个要求:

  • 如果您希望枚举为数字
  • 如果您希望枚举属于其他类型
  • 如果重构引用了不同的值,编译器会通知您
  • 最简洁的用例(减去一个字符):@Annotation(foo = MyEnum._FOO)

编辑

这样偶尔会导致编译错误,导致原来的原因element value must be a constant expression

所以这显然不是一个选择!

于 2019-06-06T14:28:11.120 回答