public class User { private String username; private String password; // Getters and setters } public class Validator { public static List<String> validate(Object obj) { List<String> errors = new ArrayList<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof NotNull) { NotNull notNull = (NotNull) annotation; try { field.setAccessible(true); Object value = field.get(obj); if (value == null) { errors.add(notNull.message()); } } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (annotation instanceof Size) { Size size = (Size) annotation; try { field.setAccessible(true); Object value = field.get(obj); if (!(value instanceof String)) { continue; } String string = (String) value; errors.add(size.message()); } } catch (IllegalAccessException e) { e.printStackTrace(); } } } } return errors; } } public class Main { public static void main(String[] args) { User user = new User(); user.setUsername(null); user.setPassword("123"); List<String> errors = Validator.validate(user); if (!errors.isEmpty()) { for (String error : errors) { System.out.println(error); } } else { } } }


上一篇:
下一篇:
切换中文