How to supply Enum value to an annotation from a Constant in Java

前端 未结 6 1163
醉话见心
醉话见心 2020-11-30 01:45

I\'m unable to use an Enum taken from a Constant as a parameter in an annotation. I get this compilation error: \"The value for annotation attribute [attribute] must be an e

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 02:03

    It seems to be defined in the JLS #9.7.1:

    [...] The type of V is assignment compatible (§5.2) with T, and furthermore:

    • [...]
    • If T is an enum type, and V is an enum constant.

    And an enum constant is defined as the actual enum constant (JLS #8.9.1), not a variable that points to that constant.

    Bottom line: if you want to use an enum as a parameter for your annotation, you will need to give it an explicit MyEnum.XXXX value. If you want to use a variable, you will need to pick another type (not an enum).

    One possible workaround is to use a String or int that you can then map to your enum - you will loose the type safety but the errors can be spotted easily at runtime (= during tests).

提交回复
热议问题