Sub topic 11
Putting it together: a small annotation-driven validator
This chapter combines the pieces from earlier chapters into one working program: a validator that reads annotations on fields and checks the values. It assumes you can already do the following:
- Obtain a
Classobject and list its declared fields. - Read and write a field with
Field.getandsetAccessible(true). - Declare an annotation with
@Retentionand@Target. - Read an annotation with
getAnnotation.
Frameworks such as Bean Validation and Jackson use this same pattern at larger scale. The code here is about 80 lines.
The design
The validator knows nothing about the classes it checks. Each class describes its own rules with annotations, and the validator discovers those rules at runtime.
Three choices shape the code:
- Return the errors instead of printing them. A list of messages can be tested, shown in a UI, or turned into an exception by the caller.
- Walk the superclass chain.
getDeclaredFields()returns only the fields declared in that exact class. - Skip static fields. Rules describe instance state, so a static field is not part of the object being checked.
Step 1: Define the rules
Two annotations are enough to show the pattern. @NotBlank has a default message. @MaxLength takes a required value and also has a message.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MaxLength {
int value();
String message() default "is too long";
}RetentionPolicy.RUNTIME is required. With the default CLASS retention, the annotation is stored in the class file but not visible to reflection, so getAnnotation returns null and the validator silently accepts everything. @Target(ElementType.FIELD) makes the compiler reject these annotations on methods or classes.
Step 2: Write the validator
This file contains the annotated model classes and the validator. Put all of it in Validator.java.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MaxLength {
int value();
String message() default "is too long";
}
class SignUp {
@NotBlank
String username;
@NotBlank(message = "email is required")
String email;
@MaxLength(8)
String nickname;
SignUp(String username, String email, String nickname) {
this.username = username;
this.email = email;
this.nickname = nickname;
}
}
class AdminSignUp extends SignUp {
@NotBlank
String role;
AdminSignUp(String username, String email, String nickname, String role) {
super(username, email, nickname);
this.role = role;
}
}
public class Validator {
static List<String> validate(Object target) {
List<String> errors = new ArrayList<>();
for (Class<?> c = target.getClass();
c != null && c != Object.class;
c = c.getSuperclass()) {
for (Field f : c.getDeclaredFields()) {
checkField(target, f, errors);
}
}
return errors;
}
private static void checkField(Object target, Field f, List<String> errors) {
if (Modifier.isStatic(f.getModifiers())) {
return;
}
NotBlank notBlank = f.getAnnotation(NotBlank.class);
MaxLength maxLength = f.getAnnotation(MaxLength.class);
if (notBlank == null && maxLength == null) {
return;
}
Object value = read(f, target);
if (notBlank != null
&& (value == null || value.toString().trim().isEmpty())) {
errors.add(f.getName() + ": " + notBlank.message());
}
if (maxLength != null && value != null) {
if (!(value instanceof CharSequence)) {
throw new IllegalStateException(
"@MaxLength needs a text field: " + f);
}
if (((CharSequence) value).length() > maxLength.value()) {
errors.add(f.getName() + ": " + maxLength.message()
+ " (max " + maxLength.value() + ")");
}
}
}
private static Object read(Field f, Object target) {
try {
f.setAccessible(true);
return f.get(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read " + f, e);
}
}
public static void main(String[] args) {
List<String> errors = validate(
new AdminSignUp("ada", "", "averyLongNickname", " "));
errors.forEach(System.out::println);
System.out.println("valid: "
+ validate(new SignUp("ada", "[email protected]", "ada")).isEmpty());
}
}Compile and run it with javac Validator.java and java Validator. On a typical JVM the output is:
role: must not be blank
username: ... (not printed, "ada" is valid)That sketch is wrong, so here is the actual output:
role: must not be blank
email: email is required
nickname: is too long (max 8)
valid: truerole comes first because the loop starts at the most specific class. The order of getDeclaredFields() within a class is unspecified by the Javadoc. HotSpot returns declaration order, but do not write tests or code that depend on it. If order matters, sort the fields by name or collect the errors into a Set.
How each step works
target.getClass()returns the runtime class, so passing anAdminSignUpthrough aSignUpvariable still checks therolefield.Modifier.isStaticfilters out static fields. Without it, an annotated static field would be read with an object it does not belong to. Reflection ignores the object for statics, so the result would still be misleading.getAnnotation(Class)returnsnullwhen the annotation is absent. Always test fornullbefore using the result.value.toString().trim().isEmpty()treats whitespace-only strings as blank. A single space inroletherefore fails. TheString.isBlank()method added in Java 11 does the same job.maxLength.value()is an annotation member. It reads like a method call because annotation members are declared as methods on the annotation interface.
Edge cases and decisions
| Situation | What the code does | Why |
|---|---|---|
| Field is `null` and has `@NotBlank` | Reports an error | `null` is a blank value |
| Field is `null` and has `@MaxLength` only | No error | Absence is `@NotBlank`'s concern, so each rule stays single-purpose |
| `@MaxLength` on an `int` field | Throws `IllegalStateException` | It is a programming mistake, so fail loudly instead of reporting a user error |
| Inherited field with a rule | Checked | The superclass loop reaches it |
| Rule on a private field | Checked | `setAccessible(true)` lifts the access check |
| `target` is `null` | `NullPointerException` at `getClass()` | Passing `null` is a caller bug |
The last decision is easy to miss: a misconfigured rule is a different kind of problem from invalid data. Invalid data goes into the returned list. A wrong annotation placement throws an exception, because the developer needs to fix the code.
Extending the validator
Adding a rule means adding one annotation and one block inside checkField. The design has one weakness: checkField grows with each rule. A common next step is a small Rule interface, one implementation per annotation, and a map from annotation type to rule. That change belongs in a larger framework. For two rules, the direct code is easier to read.
You could also support nested objects by recursing into fields annotated with a @Valid marker. If you do, track the objects you have visited, because a cyclic reference (a parent that points to a child that points back) would otherwise recurse forever.
Exercise
A teammate adds @NotBlank to a field, but the validator never reports an error for it, even for null values. The annotation declaration has @Target(ElementType.FIELD) and no @Retention. What is wrong, and what is the fix?
Show answer
Without @Retention(RetentionPolicy.RUNTIME), the annotation has the default CLASS retention. It stays in the class file but is not available through reflection, so getAnnotation(NotBlank.class) returns null and the validator skips the field. Add @Retention(RetentionPolicy.RUNTIME) to the annotation declaration.
Exercise
Add a @Min(int value) annotation for int fields and make validate report age: must be at least 18 when an age field annotated @Min(18) holds 17. Which two parts of the code change, and what type does Field.get return for an int field?
Show answer
Declare @Min with @Retention(RUNTIME), @Target(FIELD), int value() and a message(). In checkField, read f.getAnnotation(Min.class), include it in the "no rule annotations" early-return test, and add a block that checks value instanceof Integer and compares ((Integer) value) < min.value(). Field.get returns an Object, so an int field comes back boxed as an Integer. Using f.getInt(target) is an alternative that avoids boxing.