1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| @Component @Slf4j public class OnlyOneNotNullValidator implements ConstraintValidator<OnlyOneNotNull, Object> {
private String[] fieldNames;
@Override public void initialize(OnlyOneNotNull onlyOneNotNull) { this.fieldNames = onlyOneNotNull.fieldNames(); }
@Override public boolean isValid(Object object, ConstraintValidatorContext context) { if (Objects.isNull(object)) { return true; } Class clazz = object.getClass(); try { List<Field> fields = Arrays.stream(fieldNames) .map(fieldName -> ReflectionUtils.findField(clazz, fieldName)) .filter(Objects::nonNull).peek(field -> field.setAccessible(true)) .filter(field -> Objects.nonNull(ReflectionUtils.getField(field, object))) .collect(Collectors.toList());
boolean onlyOneNotNull = fields.size() == 1; if (!onlyOneNotNull) { invalid(context); } else if (fields.get(0).isAnnotationPresent(CustomValid.class)) { validate(fields.get(0).get(object)); } return onlyOneNotNull; } catch (IllegalAccessException e) { log.warn(e.getMessage(), e); return false; } catch (Exception e) { return false; } }
private void invalid(ConstraintValidatorContext context) { throw new RuntimeException(String.format("[%s]", String.join(", ", fieldNames)) + " only one filed should not be null"); } }
|