Java Record Compact Validation
Define immutable records with compact constructors for validation in Java applications.
Code
public record User(String email, int age, String role) {
public User {
if (!email.contains("@")) throw new IllegalArgumentException("invalid email");
if (age < 0 || age > 150) throw new IllegalArgumentException("invalid age");
if (!java.util.Set.of("admin", "user", "guest").contains(role))
throw new IllegalArgumentException("invalid role");
email = email.toLowerCase();
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.