我正在寻找一种简单明了的方法来将给定的数字对象转换为给定数字类型的对象。
- 由于缩小转换而导致的精度损失是可以接受的
- 我不想遍历字符串。
我需要这样的东西:
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/