码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的基本数据类型默认值扩展

时间:2016-05-23 13:15:46      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

因为在很多情况下,如果要转换的数据为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);
	}

  

Java中的基本数据类型默认值扩展

标签:

原文地址:http://www.cnblogs.com/Rong-/p/5519489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!