Search code examples
javabean-validation

Annotation return default key value


when we use annotation

@NotNull and there is a constraint validation who happen

not null return automatically his message

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Repeatable(List.class) @Documented @Constraint(validatedBy = { }) public @interface NotNull {

    String message() default "{jakarta.validation.constraints.NotNull.message}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    /**      * Defines several {@link NotNull} annotations on the same element.      *   * @see jakarta.validation.constraints.NotNull   */     @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })   @Retention(RUNTIME)     @Documented     @interface List {

        NotNull[] value();  } }

it there a way to return his key so:

jakarta.validation.constraints.NotNull.message

Solution

  • Assuming you are asking for a way to get the message key after a constraint violation was received - you should be able to do that by working with that object. In particular, what you should look for - ConstraintViolation#getMessageTemplate(). This returns the non-interpolated error message for a constraint violation. For example, having a class:

    class Test {
        @NotNull
        String string;
    
        public Test(String string) {
            this.string = string;
        }
    }
    

    and then trying to do validation of the instance of such class:

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator()
    Set<ConstraintViolation<Test>> violations = validator.validate( new Test( null ) );
    ConstraintViolation<Test> violation = violations.iterator().next();
    
    assertEquals( "{jakarta.validation.constraints.NotNull.message}", violation.getMessageTemplate() );
    

    If you are working with some frameworks and you catch an exception of ConstraintViolationException - look at ConstraintViolationException#getConstraintViolations(), which would give you that same collection of violations as in the example above.