java - Java中数值对象之间的转换

标签 java numbers

我正在寻找一种简单明了的方法来将给定的数字对象转换为给定数字类型的对象。

  • 由于缩小转换而导致的精度损失是可以接受的
  • 我不想遍历字符串。

我需要这样的东西:

private static Number convert(Number num, Class<? extends Number> targetType)

有没有办法不用检查所有类型的组合呢?

最佳答案

我认为最明确的方法是使用蛮力:

private static Number convert(Number num, Class<? extends Number> targetType) {
    Number result = null;
    if (Byte.class.equals(targetType)) {
        result = Byte.valueOf(num.byteValue());
    } else if (Short.class.equals(targetType)) {
        result = Short.valueOf(num.shortValue());
    } else if (...) {
         ...
    } else {
        throw new IllegalArgumentException("targetType is not a Number");
    }
    return result;
}

您可能会使用反射,但我发现那更骇人听闻。

关于java - Java中数值对象之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3746365/

相关文章:

javascript - javascript 中的货币四舍五入到最接近的百位

java - 如何在android中使用post数据调用webservice

java - 设置多节点集群来运行mapreduce程序

java - 如何将同一个对象的不同实例添加到Java中的LinkedList中?

xslt格式-数字小数,数字小于一

php - 如何在 PHP 中自然地对文件列表(一些以数字结尾,例如 "-2")进行排序

java - 如何通过流为 C++、Java 和 Python 交换二进制结构化数据?

更改 build.gradle 时出现 java.lang.ClassNotFoundException : javax. persistence.EntityManagerFactory

python - 简单的基本 Python 比较

javascript - 从字符串中提取数字? (JavaScript)