How can I use either enums or final Objects inside Java annotations to make better validations?

35 views Asked by At

Annotations in Java like Size or JsonProperty require me to use constants, I have lots of fields in DTOs to validate and I also need to go back to the validated fields later to check some infos so I want to group my constants, for that, i would like to use either enums or final Objects, for example

public static final MyField FIELD = new MyField (1,  "FieldName", FieldTypeEnum.TYPE, 150, 0, "Test")

or

FIELD (1, "FieldName", FieldTypeEnum.TYPE, 150, 0, "Test")

being those infos code, name, type, size, fractionSize and message;

and on my DTO i would validate my fields with something like

@Size(max = FieldEnum.FIELD.size, message = FieldEnum.FIELD.message)
@JsonProperty(FieldEnum.FIELD.name)
private String field;

But I am receiving errors such as "The value for annotation attribute Size.max must be a constant expression" for both solutions, meaning neither enums nor static objects can be used for that

I will have hundreds of fields to validate, everything with fixed constants like those, I really don't want to verbose my way out of this, is there something I can do to solve this?

Both solutions I tried (enums and static objects) weren't accepted on the annotations values I have seen some similar questions on stack overflow but they all use simpler enums so those solutions don't work for me

0

There are 0 answers