56 lines
1.5 KiB
Java
56 lines
1.5 KiB
Java
package com.diagnose.common.validation;
|
|
|
|
import com.google.common.collect.Sets;
|
|
|
|
import javax.validation.Constraint;
|
|
import javax.validation.ConstraintValidator;
|
|
import javax.validation.ConstraintValidatorContext;
|
|
import javax.validation.Payload;
|
|
import java.lang.annotation.Documented;
|
|
import java.lang.annotation.Retention;
|
|
import java.lang.annotation.Target;
|
|
import java.util.Set;
|
|
|
|
import static java.lang.annotation.ElementType.*;
|
|
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
|
|
|
@Documented
|
|
@Constraint(validatedBy = IntArrayChecker.class)
|
|
@Target({METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, CONSTRUCTOR})
|
|
@Retention(RUNTIME)
|
|
public @interface IntArrayValidator {
|
|
|
|
String message() default "不符合取值范围";
|
|
|
|
Class<?>[] groups() default {};
|
|
|
|
Class<? extends Payload>[] payload() default {};
|
|
|
|
int[] value();
|
|
|
|
}
|
|
|
|
class IntArrayChecker implements ConstraintValidator<IntArrayValidator, Integer> {
|
|
|
|
private Set<Integer> AVAILABLE_VALUES;
|
|
|
|
@Override
|
|
public void initialize(IntArrayValidator validator) {
|
|
int[] values = validator.value();
|
|
Set<Integer> valuesSet = Sets.newHashSetWithExpectedSize(values.length);
|
|
for (int value : values) {
|
|
valuesSet.add(value);
|
|
}
|
|
AVAILABLE_VALUES = valuesSet;
|
|
}
|
|
|
|
@Override
|
|
public boolean isValid(Integer value, ConstraintValidatorContext context) {
|
|
if (value == null) {
|
|
return true;
|
|
} else {
|
|
return AVAILABLE_VALUES.contains(value);
|
|
}
|
|
}
|
|
|
|
} |