标签:
因为在很多情况下,如果要转换的数据为null,调用者期望的是返回默认值.
系统自动提供的默认值不能满足我们的需求,例如int的默认值为0,但是在sql查询中,如果查询失败,我们期望的是小于0的值,例如Select Count(1) from table1这样的操作.
为此,我提供了取得数据类型默认值的扩展函数
目标:
1)实现根据自己需要返回基本类型的默认值
2) 性能不要太差
1: 接口:
public static <T> T GetDefault(Class<T> t)
2: 实现
/** * 获取数据类型的默认值 * @param t * @return */ @SuppressWarnings("unchecked") public static <T> T GetDefault(Class<T> t) { if (t == Object.class) { return null; } if (t == Integer.class) { return t.cast(-1); } if (t == String.class) { return t.cast(""); } if (t == boolean.class) { Object ret = false; return (T)ret; } if (t == Boolean.class) { Object ret = false; return (T)ret; } if (t == BigDecimal.class) { return (T)(new BigDecimal(-1)); } Class<?> superClass = t.getSuperclass(); if (superClass == null) { Object val = -1; return (T)val; } if (t.getSuperclass().equals(Number.class)) { Object val = -1; return (T)val; } return null; }
3: 测试代码
@Test public void Test_HiTypeHelper_Cast() { Integer val = 1; int ret = HiTypeHelper.Cast(int.class, val); Assert.assertEquals(ret, 1); String text = "1"; ret = HiTypeHelper.Cast(int.class, text); Assert.assertEquals(ret, 1); text = "a"; ret = HiTypeHelper.Cast(int.class, text); Assert.assertEquals(ret, -1); int val2 = 1; Integer ret2 = HiTypeHelper.Cast(Integer.class, val2); Assert.assertEquals(ret2.intValue(), 1); text = "1"; ret2 = HiTypeHelper.Cast(Integer.class, text); Assert.assertEquals(ret2.intValue(), 1); boolean bl = HiTypeHelper.Cast(boolean.class, 1); Assert.assertTrue(bl); bl = HiTypeHelper.Cast(boolean.class, 3); Assert.assertTrue(bl); bl = HiTypeHelper.Cast(boolean.class, 0); Assert.assertFalse(bl); bl = HiTypeHelper.Cast(boolean.class, -1); Assert.assertFalse(bl); bl = HiTypeHelper.Cast(boolean.class, "1"); Assert.assertTrue(bl); bl = HiTypeHelper.Cast(boolean.class, "3"); Assert.assertTrue(bl); bl = HiTypeHelper.Cast(boolean.class, "0"); Assert.assertFalse(bl); bl = HiTypeHelper.Cast(boolean.class, "-1"); Assert.assertFalse(bl); }
标签:
原文地址:http://www.cnblogs.com/Rong-/p/5519489.html