[英]Method Generics Without Arguments
假设我有一个像这样的方法:
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);
作为对KennyTM建议的增强,您可以将Class参数与方法泛型组合以返回专用类型:
@SuppressWarnings("unchecked")
public static <N extends Number> N getOddBits(Class<N> cls) {
Number out;
if (cls == Byte.class) {
out = (byte)0xAA;
} else if (cls == Short.class) {
out = (short)0xAAAA;
} else if (cls == Integer.class) {
out = 0xAAAAAAAA;
} else if (cls == Float.class) {
out = Float.intBitsToFloat(0xAAAAAAAA);
} else if (cls == Long.class) {
out = 0xAAAAAAAAAAAAAAAAL;
} else if (cls == Double.class) {
out = Double.longBitsToDouble(0xAAAAAAAAAAAAAAAAL);
} else {
throw new IllegalArgumentException();
}
return (N)out;
}
这将允许您分配以下内容,并避免在每次调用时进行强制转换:
float result = Example.getOddBits(Float.class);
我不确定这是否会对您有所帮助,但我过去曾使用它来反序列化并返回相应类型的Object。
public <T> T deserialize(String xml){
T object=null;
...
//pull type information from method param
...
return object=(T)type.newInstance(); //helper to instantiate class
}
但是,我不完全确定你需要做什么。 实现这一目标的更简单,更简洁的方法可能是为您需要的给定类型创建一个Converter接口,并使用它所需的任何类来实现它。 那么你需要什么类型的东西,可以直接在Object本身上调用。 例如:
inerface Convertor<T>{
T convert();
void set(T value);
}
class Something implements Converter<Long,ByteArray>{
...
public ByteArray convert(){...}
public void set(ByteArray value){...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.