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.util.Date,java.sql.date与String和long之间的转换,下面是我的实现:
/**
* 字符串转换成日期
* @param text
* @return
*/
public static java.util.Date Convert2Date(String text) {
if (text == null || text.trim() == "") {
return null;
}
String format = "yyyy-MM-dd";
String str = text.trim();
if (str.contains(":")) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 字符串转换为日期
* @param text
* @return
*/
public static java.sql.Date Convert2SqlDate(String text) {
java.util.Date dt = Convert2Date(text);
return new java.sql.Date(dt.getTime());
}
/**
* 日期转换为字符串
* @param date
* @return
*/
public static String ToShortString(java.util.Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* 日期转换为字符串
* @param date
* @return
*/
public static String ToLongString(java.util.Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* 日期转换为字符串
* @param date
* @return
*/
public static String ToShortString(java.sql.Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* 日期转换为字符串
* @param date
* @return
*/
public static String ToLongString(java.sql.Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}