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

    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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值