public class Validate {
public static final String ALL_FIELDS = "ALL";
public static final String INCLUDE_FIELDS = "INCLUDE";
public static final String EXCLUDE_FIELDS = "EXCLUDE";
/**
* 实体属性非空校验
*
* @param obj 实体
* @param checkAll 校验所有属性
*/
public static void validate(Object obj, String checkAll) {
Field[] fields = obj.getClass().getDeclaredFields();
List<String> keySet = Arrays.stream(fields).map(Field::getName).collect(Collectors.toList());
if (ALL_FIELDS.equalsIgnoreCase(checkAll)) {
validate(obj, keySet);
}
}
/**
* @param obj 实体
* @param checkPart include or exclude
* @param part 待校验属性
*/
public static void validate(Object obj, String checkPart, Collection<String> part) {
Field[] fields = obj.getClass().getDeclaredFields();
if (INCLUDE_FIELDS.equalsIgnoreCase(checkPart)) {
validate(obj, part);
}
if (EXCLUDE_FIELDS.equalsIgnoreCase(checkPart)) {
List<String> check = Arrays.stream(fields).map(Field::getName).filter(f -> !part.contains(f)).collect(Collectors.toList());
validate(obj, check);
}
}
/**
* @param map 校验map
* @param checkSet 待校验key
*/
public static void validate(Map<String, Object> map, Collection<String> checkSet) {
List<String> notNull = new ArrayList<>();
for (String check : checkSet) {
for (String key : map.keySet()) {
if (!check.equals(key)) {
continue;
}
String value = map.get(check) == null ? "" : String.valueOf(map.get(check));
if (value == null || "".equals(value)) {
notNull.add(key);
}
break;
}
}
List<String> notAppear = checkSet.stream().filter(k -> !map.containsKey(k)).collect(Collectors.toList());
notNull.addAll(notAppear);
if (!notNull.isEmpty()) {
throw new RuntimeException("参数 " + notNull + " 不可为空!");
}
}
private static void validate(Object obj, Collection<String> checkSet) {
Field[] fields = obj.getClass().getDeclaredFields();
List<String> notNull = new ArrayList<>();
try {
for (String check : checkSet) {
for (Field field : fields) {
// 打开私有属性,否则只能获取到共有属性
field.setAccessible(true);
String name = field.getName();
if (!check.equals(name)) {
continue;
}
String value = field.get(obj) == null ? "" : String.valueOf(field.get(obj));
if (value == null || "".equals(value)) {
notNull.add(name);
}
break;
}
}
if (!notNull.isEmpty()) {
throw new RuntimeException("参数 " + notNull + " 不可为空!");
}
} catch (IllegalAccessException e) {
throw new RuntimeException("校验失败,异常堆栈信息:" + e);
}
}
}