0
@Data
public class TestData {

    private Integer x;
    private Integer y;

    @AssertTrue
    public boolean isValid() {
        String message;

        if (x > y) {
            message = "message1..."; // here
            return false;
        }
        else if (x < y) {
            message = "messsage2..." // and here
            return false;
        }
        else {
            return true;
        }
    }

}

I know it's possible to set the message in the @AssertTrue annotation (@AssertTrue(message = "default messsage")), but I wonder if there is a way to dynamically set the message at runtime.

QIAOMO
  • 1

1 Answers1

-2

In Java, the message of an @AssertTrue cannot be set dynamically at runtime. The value of the message attribute in an annotation must be a constant expression known at compile time.

If you need a dynamic message based on certain conditions, you must consider using custom validation logic instead of relying solely on the @AssertTrue annotation. In such a situation, we implement the validator as a function that can be used for validation with a custom annotation.

To deploy the custom validation logic as a custom annotation, you can define a new annotation and use it to mark the fields or methods that require validation. Here's an example of how you can do that:

import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface CustomValidation {
    String message();
}

Next, you can modify the TestData class to use this custom annotation:

public class TestData {

private Integer x;
private Integer y;

@CustomValidation(message = "message1...")
public boolean isXGreaterThanY() {
    return x > y;
}

@CustomValidation(message = "message2...")
public boolean isXLessThanY() {
    return x < y;
}

public boolean isValid() {
    if (isXGreaterThanY() || isXLessThanY()) {
        throw new ValidationException(getValidationMessage());
    } else {
        return true;
    }
}

private String getValidationMessage() {
    try {
        CustomValidation annotation = getClass()
                .getMethod("isValid")
                .getDeclaredAnnotation(CustomValidation.class);
        return annotation.message();
    } catch (NoSuchMethodException e) {
        // Handle exception appropriately
        return "Default validation error message";
    }
}

private static class ValidationException extends RuntimeException {
    public ValidationException(String message) {
        super(message);
    }
}

}

Soheil Babadi
  • 562
  • 2
  • 4
  • 15