Jason S
Jason S

Reputation: 189806

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().

Upvotes: 1

Views: 325

Answers (1)

mut1na
mut1na

Reputation: 795

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)

Upvotes: 1

Related Questions