您的位置:首页 > 编程语言 > Java开发

关于泛型的一点应用(数值类型间的转换)

2016-06-02 09:12 483 查看
private static Map<Class<? extends Number>, Constructor> constructorMap = Maps.newHashMap();
static {
// Integer Long Short Byte Double Float BigDecimal cache constructor method
try {
constructorMap.put(Integer.class, Integer.class.getConstructor(String.class));
constructorMap.put(Long.class, Long.class.getConstructor(String.class));
constructorMap.put(Short.class, Short.class.getConstructor(String.class));
constructorMap.put(Byte.class, Byte.class.getConstructor(String.class));
constructorMap.put(Double.class, Double.class.getConstructor(String.class));
constructorMap.put(Float.class, Float.class.getConstructor(String.class));
constructorMap.put(BigDecimal.class, BigDecimal.class.getConstructor(String.class));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}

缓存常用数值类型 的反射方法 (频繁利用反射查找类内容 会影响性能)

/**
* 将未知number对象转换到具体类
* @param source 源对象
* @param targetClass 目标类
* @param <T>
* @param <E>
* @return
*/
public static <T, E extends Number> E number2Target(T source, Class<E> targetClass) {
if (targetClass.isPrimitive()) {
throw new RuntimeException("targetClass should not be a basic type!");
}
try {
Constructor<E> constructor = constructorMap.get(targetClass);
if (source == null) return constructor.newInstance("0");
if (!(source instanceof Number)) {
throw new RuntimeException("source should be a number!");
}
String number = source.toString();
if (number.contains(".") && (targetClass.equals(Integer.class)
|| targetClass.equals(Short.class) || targetClass.equals(Long.class)
|| targetClass.equals(Byte.class))) {
return constructor.newInstance(number.substring(0, number.indexOf(".")));
}
return constructor.newInstance(number);
} catch (InstantiationException e) {
throw new ApolloRuntimeException("targetClass is no such constructor: TargetClass(String s)");
} catch (IllegalAccessException e) {
throw new ApolloRuntimeException("The constructor of targetClass is private, no permissions to access");
} catch (InvocationTargetException e) {
throw new ApolloRuntimeException("The constructor is error in processing");
}
}


利用泛型 跟反射 转换未知的number对象 为目标number对象 由于利用到了构造方法 so 基础类型无法使用

(欢迎大家指正 改造。。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息