bean验证公用方法
package com.gg.common.beanvalidator;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.gg.common.beanvalidator.annotation.CheckLatLon;
import com.gg.common.beanvalidator.annotation.CheckLength;
import com.gg.common.beanvalidator.annotation.CheckNull;
import com.gg.common.beanvalidator.annotation.CheckNum;
import com.gg.common.beanvalidator.annotation.LatLon;
import com.gg.common.persistence.DataEntity;
/**
* 验证bean的属性有效
*
*
*/
public class ValidationUtil {
public static Map<String, Object> doValidatorSingle(Object clas) {
Map<String, Object> remap = new HashMap<String, Object>();
Field[] fields = getAllFields(clas);
for (Field field : fields) {
Object value = getValue(clas, field.getName());
CheckNull checkNull = field.getDeclaredAnnotation(CheckNull.class);
List<Object> ls = new ArrayList<Object>();
if (null != checkNull) {
if (!notNull(value)) {
ls.add(checkNull.message());
}
}
CheckLength checkLength = field.getDeclaredAnnotation(CheckLength.class);
if (null != checkLength) {// 长度验证
if (!checkDataLength(value, checkLength.maxLength())) {
ls.add(String.format(checkLength.message(),checkLength.maxLength()));
}
}
CheckNum checkNum = field.getDeclaredAnnotation(CheckNum.class);
if (null != checkNum) {//数字验证
value = (null ==value)?"":value;
if (!isNumber(value.toString())) {
ls.add(checkNum.message());
}
}
//嵌套类List属性验证
if(field.getType() == java.util.List.class){
// 如果是List类型,得到其Generic的类型
Type genericType = field.getGenericType();
if(genericType == null)
continue;
// 如果是泛型参数的类型
if(genericType instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType) genericType;
//得到泛型里的class类型对象
Class<?> genericClazz = (Class<?>)pt.getActualTypeArguments()[0];
if(DataEntity.class.isAssignableFrom(genericClazz)){
value = (null ==value)?new ArrayList<Object>():value;
List<Object> list = (ArrayList<Object>)value;
for(int i=0;i<list.size();i++){
Object obj = list.get(i);
Map<String, Object> errors = doValidatorSingle(obj);
if (errors.size() > 0) {// 存在错误验证信息
remap.put(field.getName()+"["+i+"]", errors.toString());
}
}
}
}
}
if (ls.size() > 0) {// 存在错误验证信息
remap.put(field.getName(), ls);//提示消息
}
}
return remap;
}
/**
* 获取类的所有属性
*
* @param object
* @return
*/
public static Field[] getAllFields(Object object) {
if(object == null){
return new Field[0];
}
Class<?> clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
/**
* 获取当前fieldName对应的值
*
* @param clas
* 对应的bean对象
* @param fieldName
* bean中对应的属性名称
* @return
*/
public static <T> Object getValue(T clas, String fieldName) {
Object value = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clas.getClass());
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : props) {
if (fieldName.equals(property.getName())) {
Method method = property.getReadMethod();
value = method.invoke(clas, new Object[] {});
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
/**
* 非空校验
*
* @param value
* @return
*/
public static boolean notNull(Object value) {
if (null == value) {
return false;
}
if (value instanceof String && isEmpty((String) value)) {
return false;
}
if (value instanceof List && isEmpty((List<?>) value)) {
return false;
}
return null != value;
}
public static boolean isEmpty(String str) {
return null == str || str.isEmpty();
}
public static boolean isEmpty(List<?> list) {
return null == list || list.isEmpty();
}
/**
* 检查字段长度,根据注解的条件判断
*
* @return
*/
public static boolean checkDataLength(Object value, int maxLength) {
// System.out.println("-----maxLength:"+maxLength+"-----------checkDataLength:"+value);
if (null != value && value.toString().length() > 0 && value.toString().length() <= maxLength) {
return true;
} else if (null == value || value.toString().length() == 0) {
return true;
}
return false;
}
/**
* 检查日期的格式化 不验证非空,只检查非空时的格式化
*
* @param value
* @param maxLength
* @return
*/
public static boolean checkDateFormate(Object value, String formate) {
if (null != value && value.toString().length() > 0) {
SimpleDateFormat sf = new SimpleDateFormat(formate);
Date d = new Date();
try {
d = sf.parse(value.toString());
} catch (ParseException e) {
return false;// 返回错误格式数据
}
}
return true;
}
/**
* 经纬度验证
*
* @return
*/
public static boolean checkLatLon(LatLon type, String value) {
String reglo = "((?:[0-9]|[1-9][0-9]|1[0-7][0-9])\\.([0-9]{0,15}))|((?:180)\\.([0]{0,15}))";
String regla = "((?:[0-9]|[1-8][0-9])\\.([0-9]{0,15}))|((?:90)\\.([0]{0,15}))";
if (StringUtils.isNotEmpty(value)) {
value = value.trim();
switch(type){
case LatLon:
String[] temp = value.split(",");
if(temp!=null && temp.length==2){
return temp[0].matches(regla)&&temp[1].matches(reglo)? true : false;
}else{
return false;
}
case Lat:
return value.matches(regla) ? true : false;
case Lon:
return value.matches(reglo) ? true : false;
}
}
return true;
}
public static boolean isNumber(String str){
if(null == str || str.length()==0){
return true;
}
String reg = "^[0-9]+(.[0-9]+)?$";
return str.matches(reg);
}
}