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

前端 未结 6 1167
醉话见心
醉话见心 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:17

    My solution was

    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();
    }
    

    I thought this was the cleanest way. This meets couple of requirements:

    • If you want the enums to be numeric
    • If you want the enums to be of some other type
    • Compiler notifies you if a refactor references a different value
    • Cleanest use-case (minus one character): @Annotation(foo = MyEnum._FOO)

    EDIT

    This leads occasionally to compilation error, which leads to the reason of the original element value must be a constant expression

    So this is apparently not an option!

提交回复
热议问题