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?
I really wish I or someone else could give you a different answer, but no, there is no other way that works better. In cases like this, we're all stuck using a class full of static final Strings. The way you tried to make it work ought to work, but it doesn't. For now, this is just the way it is in Java. I ran into this problem myself once, and I too was annoyed to find that Enums can't be treated like constant expressions. I feel your pain and, again, I wish I could give you a different answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With