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

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

    "All problems in computer science can be solved by another level of indirection" --- David Wheeler

    Here it is:

    Enum class:

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

    Person class:

    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 {
    ...
    }
    

提交回复
热议问题