I am writing Java code that uses Jackson for JSON serialization. One annotation that I must use before one my classes is @JsonTypeName(/*Insert string here*/)
, in order to give an object of this class a unique identifier for serialization. In my current code, we set the String argument by using a global constant from another class. Example:
public class AnnotationValues {
private static final String id1 = "1";
private static final String id2 = "2";
private static final String id3 = "3";
// And so on...
}
Using this class, our annotation would look like @JsonTypeName(AnnotationValues.id1)
. I personally do not think that this is a very robust coding style, to use a class of global String constants. This would become annoying once my application needs to handled a larger quantity of JSON messages and thus require many different identifiers. I naturally would solve this problem, in general, by using an enum
. I would replace the class with:
public enum AnnotationValues {
ID1("1"),
STATS_RESPONSE("2"),
SESSION_RESPONSE("3"),
/* Add more... */;
public final String value;
private AnnotationValues(String value) {
this.value = value;
}
}
Using this enum, I want to write @JsonTypeName(AnnotationsValues.ID1.value)
as my annotation. But this doesn't work. I get this error message: "The value for annotation attribute JsonTypeName.value must be a constant expression". A simple Google/SOF search lead me to this SOF post telling me why this was an error; a String value for an annotation parameter must be a constant. Pretty annoying that I can't use an enum
.
Does anyone else run into this problem? What is the accepted solution for this type of problem? Am I really supposed to use a long list of String constants for my annotations? Is there any way I can salvage using my Enum? Anything else?