Object轉String、double、long、int、boolean工具類apache
package com.myframework.utils; import org.apache.commons.lang3.StringUtils; public final class CastUtil { /** * obj轉爲String型 * * @param obj * @return */ public static String castString(Object obj) { return castString(obj, ""); } /** * object轉成String類型 * @param obj * @param defaultValue * @return */ public static String castString(Object obj, String defaultValue) { return obj != null ? String.valueOf(obj) : defaultValue; } /** * object轉成double類型 * @param obj * @return */ public static double castDouble(Object obj) { return castDouble(obj, 0); } /** * object轉成double類型 * @param obj * @param defaultValue * @return */ public static double castDouble(Object obj, double defaultValue) { double value = defaultValue; if (obj == null) { return value; } String strValue = castString(obj); if (StringUtils.isNotEmpty(strValue)) { try { value = Double.parseDouble(strValue); } catch (NumberFormatException e) { value = defaultValue; } } return value; } /** * Object轉成long型 * @param obj * @return */ public static long castLong(Object obj) { return castLong(obj, 0); } /** * Object轉成long型 * @param obj * @param defaultValue * @return */ public static long castLong(Object obj, long defaultValue) { long value = defaultValue; if (obj == null) { return value; } String strValue = castString(obj); if (StringUtils.isNotEmpty(strValue)) { try { value = Long.parseLong(strValue); } catch (NumberFormatException e) { value = defaultValue; } } return value; } /** * Object轉成int型 * @param obj * @return */ public static int castInt(Object obj) { return castInt(obj,0); } /** * Object轉成int型 * @param obj * @param defaultValue * @return */ public static int castInt(Object obj, int defaultValue) { int value = defaultValue; if (obj == null) { return value; } String strValue = castString(obj); if (StringUtils.isNotEmpty(strValue)) { try { value = Integer.parseInt(strValue); } catch (NumberFormatException e) { value = defaultValue; } } return value; } /** * Object轉成boolean型 * @param obj * @return */ public static boolean castBoolean(Object obj) { return castBoolean(obj,false); } /** * Object轉成boolean型 * @param obj * @param defaultValue * @return */ public static boolean castBoolean(Object obj, boolean defaultValue) { boolean value = defaultValue; if (obj != null) { value = Boolean.parseBoolean(castString(obj)); } return value; } }