Skip to content

Validator

Bawnorton edited this page Aug 4, 2025 · 6 revisions

@Validator provides @Configurable with how the field should be validated and how errors should be reported.

Validator Method

the value attribute of @Validator expects a method reference for a method that is public, static, returns a boolean and accepts a parameter of the type of the annotated field.
The method reference should be in the format package.to.ClassName#methodName.
If the method is in the same class, you can omit the class reference: methodName.

For Example:

@Configurable(validator = @Validator("mustBe42"))
public static int myField = 42;

public static boolean mustBe42(int value) {
  return value == 42;
}

Fallback

Defaults to true and determines whether the field should fallback to the value assigned at compile time when it cannot be parsed or violates its @Validator

Message

Custom error message literal or method to be used if the validation fails and fallback is set to false.

If a more complex message is needed, you can pass a method reference to a custom message provider. The method must be public, static, accept a single parameter of the type of the annotated field, and return a String.
The method reference should be in the format package.to.ClassName#methodName.
If the method is in the same class, you can omit the class reference: methodName.

For Example:

@Configurable(
     validator = @Validator(
         message = "getErrorMessage",
         min = 20,
         max = 50
     )
)
public static int myField = 42;

@Configurable(validator = @Validator(message = "you done goofed"))
public static String myString = "this is a string";

public static String getErrorMessage(@Nullable Integer readValue) {
     return "Value must be between 20 and 50, but was " + readValue;
}

Note

If the field is missing or its value cannot be parsed, the argument passed to the method will be null.

Min/Max

For numeric fields instead of relying on a validator method for constraints you can simply provide a minimum and maximum value. Configurable can tell the difference between the attributes being set or not and will warn you if you also provide a validator method as the min/max will be ignored if that is the case.

Clone this wiki locally