plus.jdk.FormatValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of validator-plus Show documentation
Show all versions of validator-plus Show documentation
A simple input parameter verification component
The newest version!
package plus.jdk;
import plus.jdk.ananotaions.Validated;
import plus.jdk.ananotaions.ValidationRule;
import plus.jdk.common.IValidator;
import plus.jdk.common.ValidateException;
import java.lang.reflect.Field;
import java.util.Map;
public class FormatValidator {
public void validate(Object object) throws ValidateException {
if(object instanceof Iterable) {
for(Object obj: (Iterable>)object) {
validate(obj);
}
return;
}
if(object instanceof Map) {
for(Object obj: ((Map, ?>) object).values()) {
validate(obj);
}
}
if(object instanceof Object[]) {
for(Object obj: (Object[]) object) {
validate(obj);
}
return;
}
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
Object value = null;
try{
value = field.get(object);
}catch(Exception ignored){}
if(field.getDeclaredAnnotationsByType(Validated.class).length > 0 && value != null) {
validate(value);
}
ValidationRule[] validationRules = field.getDeclaredAnnotationsByType(ValidationRule.class);
for(ValidationRule rule : validationRules) {
IValidator validator;
try {
validator = rule.validator().newInstance();
}catch (Exception ignored){
continue;
}
if(rule.required() && value == null) {
throw new ValidateException(rule.message());
}
validator.validate(rule, name, value, field, object, rule.args());
}
}
}
}