How to chain checks in java

前端 未结 2 692
难免孤独
难免孤独 2021-01-06 08:11

Consider a class like the following

public class MyClass {

    private Integer myField;
    private Result result;
    // more global variables

    public          


        
2条回答
  •  盖世英雄少女心
    2021-01-06 08:41

    You could use Hibernate Validator (or another implementation of the JSR 303/349/380 Bean Validation standards).

    Example user class that throws an exception when being instantiated with invalid arguments. You can check all the built in constraints in the docs

        public final class User {
    
          @NotNull
          private final String username;
    
          @NotNull
          private final String firstName;
    
          @NotNull
          private final String lastName;
    
          public User(String username, String firstName, String lastName) {
            this.username = username;
            this.firstName = firstName;
            this.lastName = lastName;
    
            MyValidator.validate(this);
          }
          // public getters omitted
        }
    

    And the validator class:

    import java.security.InvalidParameterException;
    import java.util.Set;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    
    public final class MyValidator {
    
        public static void validate(Object object) {
    
          ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
          Validator validator = factory.getValidator();
    
          Set> constraintViolations = validator.validate( object );
    
          if (!constraintViolations.isEmpty()) {
              ConstraintViolation firstViolation = constraintViolations.iterator().next();
    
              throw new InvalidParameterException("not valid "
              + object.getClass()
              + " failed property ' " + firstViolation.getPropertyPath() + " ' "
              + " failure message ' " + firstViolation.getMessage() + " ' ");
          }
        }
    }
    
    
    

    And message:

    java.security.InvalidParameterException: not valid class com.foo.bar.User failed property ' firstName ' failure message ' may not be null '

    Don't forget to include the dependency in your pom.xml (if you use Maven)

    
        org.hibernate
        hibernate-validator
        5.4.1.Final
    
    

    提交回复
    热议问题