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

java:运行时等效于数值类型之间的转换,java,casting,primitive-types,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 instanc

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

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
//给定一个基元(或装箱基元)编号类,
//返回该类的装箱实例的数字,
//与相应的基本体强制转换的值相等
//(否则会引发IllegalArgumentException)
公共编号runtimeNumericCast(编号sourceNumber,
类结果类型)
{
...
}
编号obj1=3;//真的是一个整数吗
数字obj2=runtimeNumericCast(obj1,Float.class);//将返回3.0f
Number obj3=runtimeNumericCast(obj2,int.class)//将返回3
Number obj4=runtimeNumericCast(obj3,Short.class)//将返回(Short)3

我能想到的最好的方法是使用
Map,这是我应该使用的方法,除了方法签名以避免不必要的强制转换:

public <T extends Number> T runtimeNumericCast(Number sourceNumber, 
         Class<T> resultType)
公共T runtimeNumericCast(数字源编号, 类结果类型)
除了方法签名以避免不必要的强制转换之外,我本应该这样做:

public <T extends Number> T runtimeNumericCast(Number sourceNumber, 
         Class<T> resultType)
公共T runtimeNumericCast(数字源编号, 类结果类型) +1,好主意(虽然不适用于
int.class
Integer.class
因为
int.class
不同)+1,好主意(虽然不适用于
int.class
Integer.class
因为
int.class
不同)