1
我能做到这一点,当我知道在编译时的对象类型:的java:运行时相当于数字类型间铸造的
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,好主意(虽然不适合'int.class'与'整数工作.class'因为'int.class'是不同的) – 2011-05-18 18:45:44