FieldValid
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.TYPE ,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldValid {
String value() default "";
String name() default "";
boolean required() default true;
String msg() default "";
String[] condition() default {};
}
ReflectUtil
import com.sinosoft.application.claim.dto.custom.FieldValid;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
public class ReflectUtil {
public static <T> Object getFieldVal(String fieldName, T t) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> clazz = t.getClass();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = clazz.getMethod(getter);
return method.invoke(t);
}
public static <T,V> Object setFieldVal(String fieldName, T t, Class<V> clazzType, V val) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> clazz = t.getClass();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String setter = "set" + firstLetter + fieldName.substring(1);
Method method = clazz.getMethod(setter, clazzType);
return method.invoke(t, val);
}
public static <T> String valid( T t, String... conditionStr ) throws IllegalAccessException {
Class<?> clazz = t.getClass();
Field[] declaredFields = clazz.getDeclaredFields();
if(declaredFields == null || declaredFields.length <= 0){
return null;
}
for (Field field : declaredFields) {
FieldValid fieldValid = field.getAnnotation(FieldValid.class);
if(fieldValid == null){
continue;
}
boolean required = fieldValid.required();
String[] condition = fieldValid.condition();
Object objVal = null;
try {
objVal = getFieldVal(field.getName(), t);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if(required){
if(objVal == null){
return fieldValid.msg();
}
}
if(conditionStr != null && condition.length > 0){
List<String> condList = Arrays.asList(condition);
for (String cond : conditionStr) {
boolean contains = condList.contains(cond);
if(contains && objVal == null) {
return fieldValid.msg();
}
}
}
}
return null;
}
}
使用
@FieldValid(name = "操作类型",msg = "操作类型[actionType]必传")
private String actionType;
@FieldValid(name = "姓名",msg = "姓名[clientName]必传" , condition = ENUM_1.RECOGNIZE, required = false)
private String clientName;
----
String valid = ReflectUtil.valid(eleDocRequestDto);
if(valid != null){
return valid ;
}