简体   繁体   English

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

[英]java: runtime equivalent of casting between numeric types

I can do this when I know the object types at compile-time: 当我在编译时知道对象类型时,可以这样做:

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

What's the most efficient simple way to produce the same conversion between numeric types, with object types known at runtime? 在运行时已知对象类型的情况下,在数字类型之间产生相同转换的最有效的简单方法是什么?

// 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

The best I can think of is to use a Map<Class<?>, Function<Number,Number>> and declare one function for each of the 6 numeric primitive types to return Number.byteValue() , Number.shortValue() , Number.intValue() , Number.longValue() , Number.floatValue() , and Number.doubleValue() . 我能想到的最好的方法是使用Map<Class<?>, Function<Number,Number>>并为6个数字原始类型中的每个声明一个函数以返回Number.byteValue()Number.shortValue()Number.intValue()Number.longValue()Number.floatValue()Number.doubleValue()

That's the way I would have done it, except for the method signature to avoid unnecessary casting: 这就是我会做的方法,除了方法签名可以避免不必要的转换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM