Utils-verifyType 验证数据类型,是否允许转型
package com.utils;
import java.text.SimpleDateFormat;
import java.util.*;
import com.exception.ExceptionEnum;
import com.exception.MyException;
import javafx.beans.binding.When;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Case;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VerifyUtils {
public static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
/**
* 验证数据原值类型
* 返回 key 原值类型, value 值
* @param obj
* @return
* by ChenYb date 2019-05-16
*/
public static Map verifyType(Object obj){
Map result = null;
if (null == obj){
result = new HashMap<>();
result.put("null",null);
} else if (obj instanceof Integer) {
int i = ((Integer) obj).intValue();
result = new HashMap<>();
result.put("Integer",i);
}else if (obj instanceof String) {
String s = (String) obj;
result = new HashMap<>();
result.put("String",s);
} else if (obj instanceof Double) {
double d = ((Double) obj).doubleValue();
result = new HashMap<>();
result.put("Double",d);
} else if (obj instanceof Float) {
float f = ((Float) obj).floatValue();
result = new HashMap<>();
result.put("Float",f);
} else if (obj instanceof Long) {
long l = ((Long) obj).longValue();
result = new HashMap<>();
result.put("Long",l);
} else if (obj instanceof Boolean) {
boolean b = ((Boolean) obj).booleanValue();
result = new HashMap<>();
result.put("Boolean",b);
} else if (obj instanceof Date) {
Date d = (Date) obj;
result = new HashMap<>();
result.put("Date",d);
}
return result;
}
/**
* 验证数据能否成功转型
* obj 原值 ; type 类型,不区分大小写,非Date类型,可以简写,比如,Integer : int String : s
* @param obj
* @param type
* @return
* by ChenYb date 2019-05-16
*/
public static boolean verifyType(Object obj,String type){
boolean config = false;
if (null == obj || StringUtils.isEmpty(type)||StringUtils.isBlank(type))
return config;
try {
if ("INTEGER".contains(type.toUpperCase()))
Integer.valueOf(String.valueOf(obj));
else if ("STRING".contains(type.toUpperCase())){
if (obj instanceof Date)
new SimpleDateFormat("yyyy-MM-dd").format((Date) obj);
else
String.valueOf(obj);
}
else if ("DOUBLE".contains(type.toUpperCase()))
Double.valueOf(String.valueOf(obj));
else if ("FLOAT".contains(type.toUpperCase()))
Float.valueOf(String.valueOf(obj));
else if ("LONG".contains(type.toUpperCase()))
if (obj instanceof Date)
((Date) obj).getTime();
else
Long.valueOf(String.valueOf(obj));
else if ("BOOLEAN".contains(type.toUpperCase()))
Boolean.valueOf(String.valueOf(obj));
else if ("DATE".equals(type.toUpperCase())) {
if (obj instanceof Long)
new Date(((Long) obj).longValue());
else
new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(obj));
}
config = true;
}catch (Exception e){
logger.debug("obj : {},不允许转型 {}",obj,type.toUpperCase());
}
return config;
}
}