16

如何使用休眠注释来验证枚举成员字段?以下不起作用:

enum UserRole {
   USER, ADMIN;
}

class User {
   @NotBlank //HV000030: No validator could be found for type: UserRole.
   UserRole userRole;
}
4

4 回答 4

41

请注意,您还可以创建一个验证器来检查字符串是否是枚举的一部分。

public enum UserType { PERSON, COMPANY }

@NotNull
@StringEnumeration(enumClass = UserCivility.class)
private String title;

@Documented
@Constraint(validatedBy = StringEnumerationValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, CONSTRUCTOR })
@Retention(RUNTIME)
public @interface StringEnumeration {

  String message() default "{com.xxx.bean.validation.constraints.StringEnumeration.message}";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};

  Class<? extends Enum<?>> enumClass();

}

public class StringEnumerationValidator implements ConstraintValidator<StringEnumeration, String> {

  private Set<String> AVAILABLE_ENUM_NAMES;

  @Override
  public void initialize(StringEnumeration stringEnumeration) {
    Class<? extends Enum<?>> enumSelected = stringEnumeration.enumClass();
    //Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
    Set<? extends Enum<?>> enumInstances = Sets.newHashSet(enumSelected.getEnumConstants());
    AVAILABLE_ENUM_NAMES = FluentIterable
            .from(enumInstances)
            .transform(PrimitiveGuavaFunctions.ENUM_TO_NAME)
            .toSet();
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if ( value == null ) {
      return true;
    } else {
      return AVAILABLE_ENUM_NAMES.contains(value);
    }
  }

}

这很好,因为您不会丢失“错误值”的信息。你可以收到这样的消息

值“someBadUserType”不是有效的 UserType。有效的 UserType 值为:PERSON、COMPANY


编辑

对于那些想要非 Guava 版本的人来说,它应该与以下内容一起使用:

public class StringEnumerationValidator implements ConstraintValidator<StringEnumeration, String> {

  private Set<String> AVAILABLE_ENUM_NAMES;

  public static Set<String> getNamesSet(Class<? extends Enum<?>> e) {
     Enum<?>[] enums = e.getEnumConstants();
     String[] names = new String[enums.length];
     for (int i = 0; i < enums.length; i++) {
         names[i] = enums[i].name();
     }
     Set<String> mySet = new HashSet<String>(Arrays.asList(names));
     return mySet;
  }

  @Override
  public void initialize(StringEnumeration stringEnumeration) {
    Class<? extends Enum<?>> enumSelected = stringEnumeration.enumClass();
    AVAILABLE_ENUM_NAMES = getNamesSet(enumSelected);
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if ( value == null ) {
      return true;
    } else {
      return AVAILABLE_ENUM_NAMES.contains(value);
    }
  }

}

要自定义错误消息并显示适当的值,请检查:https ://stackoverflow.com/a/19833921/82609

于 2013-08-13T13:07:57.210 回答
13

@NotBlank

验证带注释的字符串不为 null 或为空。NotEmpty 的不同之处在于尾随空格被忽略。

哪里 asUserRole不是 String 和一个object Use@NotNull

带注释的元素不能为空。接受任何类型。

于 2013-08-13T09:51:58.863 回答
7

我想与上面塞巴斯蒂安的答案更密切相关,代码行更少,并以警告EnumSet.allOf为代价使用rawtypes

枚举设置

public enum FuelTypeEnum {DIESEL, PETROL, ELECTRIC, HYBRID, ...}; 
public enum BodyTypeEnum {VAN, COUPE, MUV, JEEP, ...}; 

注释设置

@Target(ElementType.FIELD) //METHOD, CONSTRUCTOR, etc.
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValidator.class)
public @interface ValidateEnum {
    String message() default "{com.xxx.yyy.ValidateEnum.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    Class<? extends Enum<?>> targetClassType();
}

验证器设置

public class EnumValidator implements ConstraintValidator<ValidateEnum, String> {
    private Set<String> allowedValues;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void initialize(ValidateEnum targetEnum) {
        Class<? extends Enum> enumSelected = targetEnum.targetClassType();
        allowedValues = (Set<String>) EnumSet.allOf(enumSelected).stream().map(e -> ((Enum<? extends Enum<?>>) e).name())
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || allowedValues.contains(value)? true : false; 
    }
} 

现在继续并如下注释您的字段

@ValidateEnum(targetClassType = FuelTypeEnum.class, message = "Please select ...." 
private String fuelType; 

@ValidateEnum(targetClassType = BodyTypeEnum.class, message = "Please select ...." 
private String bodyType; 

以上假设您已Hibernate Validator设置并使用默认注释。

于 2018-06-29T21:07:30.880 回答
2

通常,尝试转换为枚举不仅仅是通过名称(这是valueOf方法的默认行为)。例如,如果您有枚举表示DayOfWeek并且您希望将整数转换为 aDayOfWeek怎么办?为此,我创建了以下注释:

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = {ValidEnumValueValidator.class})
public @interface ValidEnumValue {
    String message() default "invalidParam";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends Enum<?>> value();

    String enumMethod() default "name";

    String stringMethod() default "toString";
}
public class ValidEnumValueValidator implements ConstraintValidator<ValidEnumValue, String> {
    Class<? extends Enum<?>> enumClass;
    String enumMethod;
    String stringMethod;

    @Override
    public void initialize(ValidEnumValue annotation) {
        this.enumClass = annotation.value();
        this.enumMethod = annotation.enumMethod();
        this.stringMethod = annotation.stringMethod();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Enum<?>[] enums = enumClass.getEnumConstants();
        Method method = ReflectionUtils.findMethod(enumClass, enumMethod);

        return Objects.nonNull(enums) && Arrays.stream(enums)
                .map(en -> ReflectionUtils.invokeMethod(method, en))
                .anyMatch(en -> {
                    Method m = ReflectionUtils.findMethod(String.class, stringMethod);
                    Object o = ReflectionUtils.invokeMethod(m, value);

                    return Objects.equals(o, en);
                });
    }
}

您可以按如下方式使用它:

public enum TestEnum {
        A("test");

        TestEnum(String s) {
            this.val = s;
        }

        private String val;

        public String getValue() {
            return this.val;
        }
    }
public static class Testee {
        @ValidEnumValue(value = TestEnum.class, enumMethod = "getValue", stringMethod = "toLowerCase")
        private String testEnum;
    }

上述实现使用Spring 框架和 Java 8+ 中的ReflectionUtils

于 2019-04-24T00:13:38.293 回答