首页 > 代码库 > java-转型有风险使用许谨慎

java-转型有风险使用许谨慎

在使用类型转换时,经常会遇到类型转换错误的情况。比如 无法将String转换成int累类型等等,这里将所有的类型转换全部列举出来

保证在转换的适合不会出现错误。


import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * 
 * <strong>功能:</strong>类型转换
 * <strong>作者:</strong>Gary Huang
 * <strong>日期:</strong> 2014-3-5 
 * <strong>版权:<strong>版权所有(C) 2014,QQ 834865081
 */
@SuppressWarnings("unchecked")
public class TransformUtils {

	public static boolean toBoolean(Object obj) {

		return toBoolean(obj, false);
	}

	public static boolean toBoolean(Object obj, boolean defaultValue) {
		if (obj == null) {
			return defaultValue;
		}
		try {
			return Boolean.parseBoolean(toString(obj));
		} catch (Exception e) {
		}
		return defaultValue ;
	}

	public static byte toByte(Object obj) {
		return toByte(obj, (byte) 0);
	}

	public static byte toByte(Object obj, byte defaultValue) {
		if (obj == null) {
			return defaultValue;
		}

		if (obj instanceof Number) {
			Number number = (Number) obj;
			return number.byteValue();
		}
		String value = http://www.mamicode.com/toString(obj) ;>