java:运行时等效于数值类型之间的转换

时间:2011-05-18 17:56:10

标签: java casting primitive-types

当我在编译时知道对象类型时,我可以这样做:

int obj1 = 3;
float obj2 = (float)obj1;
int obj3 = (int)obj1;
short obj4 = (short)obj1;

在运行时已知对象类型的数值类型之间产生相同转换的最有效的简单方法是什么?

// given a primitive (or boxed primitive) number class,
// returns a number that's a boxed instance of that class, 
// equivalent in value to the appropriate primitive cast
// (otherwise throws an IllegalArgumentException)
public Number runtimeNumericCast(Number sourceNumber, 
         Class<?> resultType)
{
   ...
}

Number obj1 = 3;  // really an Integer
Number obj2 = runtimeNumericCast(obj1, Float.class); // will return 3.0f
Number obj3 = runtimeNumericCast(obj2, int.class) // will return 3
Number obj4 = runtimeNumericCast(obj3, Short.class) // will return (short)3

我能想到的最好的方法是使用Map<Class<?>, Function<Number,Number>>并为6种数字基元类型中的每一种声明一个函数,以返回Number.byteValue()Number.shortValue()Number.intValue()Number.longValue()Number.floatValue()Number.doubleValue()

1 个答案:

答案 0 :(得分:1)

这就是我要做的方式,除了方法签名以避免不必要的转换:

public <T extends Number> T runtimeNumericCast(Number sourceNumber, 
         Class<T> resultType)