Search⌘ K
AI Features

Solution: The Data Validator Framework

Explore how to create a data validator framework in Java by leveraging reflection to access class metadata at runtime. Understand the use of annotations to mark mandatory fields and how to inspect and retrieve field values, even private ones, for validation. This lesson helps you implement runtime checks that ensure important data is present and handled correctly in your applications.

We'll cover the following...
Java 25
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
// 1. Define the annotation and ensure it survives compilation
@Retention(RetentionPolicy.RUNTIME)
@interface Mandatory {}
class Validator {
public static void validate(Object obj) {
Class<?> clazz = obj.getClass();
// 2. Iterate over all declared fields (public, private, protected)
for (Field field : clazz.getDeclaredFields()) {
// 3. Check if the field is marked as Mandatory
if (field.isAnnotationPresent(Mandatory.class)) {
try {
// 4. Bypass privacy checks to read the value
field.setAccessible(true);
Object value = field.get(obj);
// 5. Validate the value
if (value == null) {
throw new RuntimeException("Field " + field.getName() + " is mandatory but null");
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to access field " + field.getName(), e);
}
}
}
}
}
class UserProfile {
@Mandatory
private String username;
private String bio;
@Mandatory
private String email;
public UserProfile(String username, String bio, String email) {
this.username = username;
this.bio = bio;
this.email = email;
}
}
public class SecurityEventLogger {
public static void main(String[] args) {
try {
System.out.println("Validating user1...");
UserProfile user1 = new UserProfile("jdoe", "Developer", "jdoe@example.com");
Validator.validate(user1);
System.out.println("User1 passed validation.");
System.out.println("Validating user2...");
UserProfile user2 = new UserProfile("guest", null, null);
Validator.validate(user2);
System.out.println("User2 passed validation.");
} catch (RuntimeException e) {
System.out.println("Validation failed: " + e.getMessage());
}
}
}
...