Sub topic 11
Putting it together: a small annotation-driven validator
This chapter combines reflection and annotations into a working validator. It assumes you can read a class's fields through reflection, call setAccessible(true), and declare an annotation with @Retention and @Target. The goal is a small version of what frameworks such as Bean Validation do.
The design
The validator has three parts:
- An annotation,
@NotBlank, marks the fields that need checking. - A class,
SignUp, uses the annotation on its fields. - A method,
validate, walks the fields of any object, finds the annotated ones, reads their values, and reports problems.
The validator never mentions SignUp. It works on any object, because it learns the structure at runtime.
The code
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;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}
class SignUp {
@NotBlank
String username;
@NotBlank(message = "email is required")
String email;
SignUp(String username, String email) {
this.username = username;
this.email = email;
}
}
public class Validator {
static void validate(Object target) throws IllegalAccessException {
for (Field f : target.getClass().getDeclaredFields()) {
NotBlank nb = f.getAnnotation(NotBlank.class);
if (nb == null) {
continue;
}
f.setAccessible(true);
Object value = f.get(target);
if (value == null || value.toString().trim().isEmpty()) {
System.out.println(f.getName() + ": " + nb.message());
}
}
}
public static void main(String[] args) throws Exception {
validate(new SignUp("ada", ""));
}
}Running this prints one line:
email: email is requiredWhy each piece is needed
@Retention(RetentionPolicy.RUNTIME)keeps the annotation in the class file and visible to reflection. With the defaultCLASSretention,getAnnotationwould returnnullfor every field, and the validator would silently report nothing.@Target(ElementType.FIELD)makes the compiler reject@NotBlankon a method or class, so misuse is caught early.getDeclaredFields()returns fields of every access level, but only for the exact class. Fields inherited from a superclass are not included. To cover them, loop overgetSuperclass()until you reachnull.getAnnotation(NotBlank.class)returns the annotation instance ornull. Callingnb.message()returns the supplied value or the declared default.setAccessible(true)lets the validator read package-private or private fields. It can fail withInaccessibleObjectExceptionif the class is in a module that does not open its package to you.
Extending it
Two small changes make the validator more useful. First, return a List<String> of errors instead of printing, so callers can decide what to do. Second, add a second annotation such as @Min(int value) and branch on which annotation each field carries. The structure stays the same: look up the annotation, read the value, apply the rule.
Exercise
A teammate adds @NotBlank to a field, but validate never reports it, even when the field is empty. The annotation declaration has @Target(ElementType.FIELD) and no @Retention. What is the cause and the fix?
Show answer
Without @Retention, the retention defaults to CLASS, so the annotation is stored in the class file but not available at runtime. getAnnotation returns null and the field is skipped. Add @Retention(RetentionPolicy.RUNTIME) to the annotation declaration.
Exercise
validate(new Admin(...)) ignores the @NotBlank fields declared in Admin's superclass User. Why, and how do you fix it?
Show answer
getDeclaredFields() returns only the fields declared in that exact class. Loop with for (Class<?> c = target.getClass(); c != null; c = c.getSuperclass()) and inspect c.getDeclaredFields() at each level.