packagecom.***.util;/*** CastUtil
* @description: 数据转型工具类
**/
public classCastUtil {/*** @Description: 转为String类型
* @Param: [obj]
*@return: java.lang.String 若是参数为null则转为空字符串*/
public staticString castString(Object obj){return CastUtil.castString(obj,"");
}/*** @Description: 转为String类型(提供默认值)
* @Param: [obj, defaultValue] 将obj转为string,若是obj为null则返回default
*@return: String*/
public staticString castString(Object obj,String defaultValue){return obj!=null?String.valueOf(obj):defaultValue;
}/*** @Description: 转为double类型,若是为null或者空字符串或者格式不对则返回0
* @Param: [obj]
*@return: String*/
public static doublecastDouble(Object obj){return CastUtil.castDouble(obj,0);
}/*** @Description: 转为double类型 ,若是obj为null或者空字符串或者格式不对则返回defaultValue
* @Param: [obj, defaultValue]
*@return: String obj为null或者空字符串或者格式不对返回defaultValue*/
public static double castDouble(Object obj,doubledefaultValue){double value = defaultValue; //声明结果,把默认值赋给结果
if (obj!=null){ //判断是否为null
String strValue = castString(obj); //转换为String
if (StringUtil.isNotEmpty(strValue)){ //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
try{
value= Double.parseDouble(strValue); //不为空则把值赋给value
}catch(NumberFormatException e){
value= defaultValue; //格式不对把默认值赋给value
}
}
}returnvalue;
}/*** 转为long型,若是obj为null或者空字符串或者格式不对则返回0
*@paramobj
*@return
*/
public static longcastLong(Object obj){return CastUtil.castLong(obj,0);
}/*** 转为long型(提供默认数值),若是obj为null或者空字符串或者格式不对则返回defaultValue
*@paramobj
*@paramdefaultValue
*@returnobj为null或者空字符串或者格式不对返回defaultValue*/
public static long castLong(Object obj,longdefaultValue){long value = defaultValue; //声明结果,把默认值赋给结果
if (obj!=null){ //判断是否为null
String strValue = castString(obj); //转换为String
if (StringUtil.isNotEmpty(strValue)){ //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
try{
value= Long.parseLong(strValue); //不为空则把值赋给value
}catch(NumberFormatException e){
value= defaultValue; //格式不对把默认值赋给value
}
}
}returnvalue;
}/*** 转为int型
*@paramobj
*@return若是obj为null或者空字符串或者格式不对则返回0*/
public static intcastInt(Object obj){return CastUtil.castInt(obj,0);
}/*** 转为int型(提供默认值)
*@paramobj
*@paramdefaultValue
*@return若是obj为null或者空字符串或者格式不对则返回defaultValue*/
public static int castInt(Object obj,intdefaultValue){int value = defaultValue; //声明结果,把默认值赋给结果
if (obj!=null){ //判断是否为null
String strValue = castString(obj); //转换为String
if (StringUtil.isNotEmpty(strValue)){ //判断字符串是否为空(是否为空只能判断字符串,不能判断Object)
try{
value= Integer.parseInt(strValue); //不为空则把值赋给value
}catch(NumberFormatException e){
value= defaultValue; //格式不对把默认值赋给value
}
}
}returnvalue;
}/*** 转为boolean型,不是true的返回为false
*@paramobj
*@return
*/
public static booleancastBoolean(Object obj){return CastUtil.castBoolean(obj,false);
}/*** 转为boolean型(提供默认值)
*@paramobj
*@paramdefaultValue
*@return
*/
public static boolean castBoolean(Object obj,booleandefaultValue){boolean value =defaultValue;if (obj!=null){ //为null则返回默认值
value = Boolean.parseBoolean(castString(obj)); //底层会把字符串和true对比,因此不用判断是否为空字符串
}returnvalue;
}
}