关闭

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

标签: java 数值类型相互转换 泛型
327人阅读 评论(0) 收藏 举报
分类:

    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 基础类型无法使用

(欢迎大家指正 改造。。)

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15159次
    • 积分:324
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:4篇
    • 译文:5篇
    • 评论:2条
    文章分类