/**
* 将HTTP请求中String类型的参数值转换为相关属性的类型。
* 支持String,yyyy-MM-dd格式的日期,基本类型及包装类,BigDecimal,BigInteger
* 修改此方法可添加对更多类型的支持
* @param value HTTP请求参数值
* @param type 属性类型
* @return 转换后的参数值
*/
private static Object parseValue(String[] value, Class type) throws ParseException, UnsupportedTypeException {
if (String.class == type)
return value[0];
if (java.util.Date.class == type )
return new SimpleDateFormat("yyyy-MM-dd").parse(value[0]);
if (boolean.class == type || Boolean.class == type)
return true;
if (char.class == type || Character.class == type)
return value[0].charAt(0);
if (int.class == type || Integer.class == type)
return Integer.valueOf(value[0]);
if (short.class == type || byte.class == type || long.class == type
|| float.class == type || double.class == type)
try { // 将值类型变更为对应的包装类型
type = Class.forName("java.lang." + type.getName().substring(0, 1)
.toUpperCase() + type.getName().substring(1));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (type.getName().startsWith("java.lang.") || type.getName().startsWith("java.math."))
try {
// return type.getMethod("valueOf", String.class).invoke(null, value[0]);
return type.getConstructor(String.class).newInstance(value[0]);
} catch (Exception e) {
throw new UnsupportedTypeException(e);
}
throw new UnsupportedTypeException();
}
2.创建自定义异常类(根据需求)
public class UnsupportedTypeException extends Exception {
public UnsupportedTypeException() {
super("不支持的类型转换");
}
public UnsupportedTypeException(Throwable e) {
super("不支持的类型转换", e);
}
}