已编辑:
要验证任一字段是否有价值,我认为您可以在类级别使用自定义验证器。思路如下:
1。
为您的注释创建接口:
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ChoiceValidator.class)
@Documented
public @interface Choice {
String[] fields();
String message() default "{Choice.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2。
创建ConstraintValidator 的实现以检查要验证的值是否在fields 中的Choice 注释内:
public class ChoiceValidator
implements ConstraintValidator<Choice, Object> {
private List<String> fields;
@Override
public void initialize(final Choice choice) {
fields = Arrays.asList(choice.fields());
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext ctx) {
int nonNullFieldCount = 0;
for (String field : fields) {
try {
final String fieldValue = BeanUtils.getProperty(value, field);
if (fieldValue != null) {
nonNullFieldCount++;
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
return nonNullFieldCount == 1;
}
}
之后,你可以像这样使用它:
@Choice(fields= {"fieldOne", "fieldTwo"})
public class Foo {
String fieldOne;
String fieldTwo;
}
原文:
我不确定我是否真的理解你的意思,但看起来你想要验证 Object 字段的 Class 类型。如果出现这种情况,您可以尝试创建自定义注释和 ConstraintValidator 来执行此操作。思路如下:
1。
为您的注释创建接口:
public @interface Choice {
Class<?>[] types();
}
2。
创建ConstraintValidator 的实现以检查要验证的值是否在types 中的Choice 注释内:
public class ChoiceValidator implements ConstraintValidator<Choice, Object> {
private List<Class<?>> clazzes;
@Override
public void initialize(Choice choice) {
clazzes = Arrays.asList(choice.types());
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
for (Class<?> clazz : clazzes) {
if (value.getClass().equals(clazz)) {
return true;
}
}
return false;
}
}
之后,你可以像这样使用它:
@Choice(types = {FieldOneType.class, FieldTwoType.class})
public class Foo {
Object someType;
}
希望这能有所帮助。