关于泛型的一点应用(数值类型间的转换)
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 基础类型无法使用
(欢迎大家指正 改造。。)
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树