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

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

    I think that the most voted answer is incomplete, since it does not guarantee at all that the enum value is coupled with the underlying constant String value. With that solution, one should just decouple the two classes.

    Instead, I rather suggest to strengthen the coupling shown in that answer by enforcing the correlation between the enum name and the constant value as follows:

    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";
        }
    }
    

    As pointed out by @GhostCat in a comment, proper unit tests must be put in place to ensure the coupling.

提交回复
热议问题