1

Enum:-

public StatusEnum {
   MISSING("00"), INVALID("01");
   ....
}

I'm trying to use these strings "MISSING", "INVALID" as an attribute field for JSR Validations:-

public class SomePojo{
 
  @NotNull(message = StatusEnum.MISSING.toString())  //this is invalid ofc, but this is what i want
  @Pattern(regexp="some pattern", message = StatusEnum.INVALID.toString())
  private string someField;

}

I need this so that when i programmatically validate an object against this class (javax validations), i want the constraintViolation object's getMessage to give me the enum string so that I can easily interpret the error.

I know i can put the strings directly but changing the enum will need change in the attributes as well which is a pain.

Jerald Baker
  • 1,121
  • 1
  • 12
  • 48

1 Answers1

0

The value for the message must be a constant expression. Instead of an Enum you can use a class with constants:

public class Status{
    public static final String MISSING = "00";
    public static final String INVALID = "01";
}

And then use it:

public class SomePojo{
  @NotNull(message = Status.MISSING)
  @Pattern(regexp="some pattern", message = Status.INVALID)
  private string someField;
}
Marc
  • 2,738
  • 1
  • 17
  • 21
  • if i do this, i can't automatically figure out the actual error in the constraintViolation object. I have to do if(violattion.message == "MISSING") {dothis();} else if (violation.message == INVALID)doThat(); and so on. It'll be easier with enum – Jerald Baker Jul 24 '20 at 10:45
  • I see, but I don't think it can't be done with an enum. What if you try to get the failing constraint in another way rather than by message? I am sure Hibernate validator provides something for that – Marc Jul 24 '20 at 12:58
  • They provide this "payload" field in the validation annotations but it's too much code for doing this simple task. – Jerald Baker Jul 25 '20 at 04:40