Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Generics Without Arguments

Tags:

java

generics

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();
like image 402
azz Avatar asked Apr 15 '13 10:04

azz


1 Answers

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);
like image 134
kennytm Avatar answered Oct 12 '22 11:10

kennytm