假设我有这样的方法:
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();
}
}
方法的实际细节并不重要。但是,要调用此方法,我们使用:
Example.<Float>getOddBits(0f);
我的问题是,是否可以编写这样一个没有常规参数的方法。没有重载,最终没有装箱。
理想情况下由以下人员调用:
Example.<Byte>getOddBits();
最佳答案
拿一个.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);
关于java - 没有参数的方法泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012729/