Let's say I have a method like this:
static class Example
{
public static <N extends Number> Number getOddBits(N type)
{
if (type instanceof Byte) return (byte)0xAA;
else if (type instanceof Short) return (short)0xAAAA;
else if (type instanceof Integer) return 0xAAAAAAAA;
else if (type instanceof Float) return Float.intBitsToFloat(0xAAAAAAAA);
else if (type instanceof Long) return 0xAAAAAAAAAAAAAAAAL;
else if (type instanceof Double) return Double.longBitsToDouble(0xAAAAAAAAAAAAAAAAL);
throw new IllegalArgumentException();
}
}
The actual specifics of the method isn't really important. However, to call this method we use:
Example.<Float>getOddBits(0f);
My question is, is it possible to write such a method without conventional parameters. Without overloading, and ultimately without Boxing.
Ideally invoked by:
Example.<Byte>getOddBits();
How about just take a .class
?
public static Number getOddBits(Class<? extends Number> cls)
{
if (cls == Byte.class) {
return (byte)0xAA;
} else if (cls == Short.class) {
return (short)0xAAAA;
} else if (cls == Integer.class) {
return 0xAAAAAAAA;
} else if (cls == Float.class) {
return Float.intBitsToFloat(0xAAAAAAAA);
} else if (cls == Long.class) {
return 0xAAAAAAAAAAAAAAAAL;
} else if (cls == Double.class) {
return Double.longBitsToDouble(0xAAAAAAAAAAAAAAAAL);
}
throw new IllegalArgumentException();
}
...
Example.getOddBits(Float.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With