我想创建一个这种形式的泛型类:
class MyGenericClass<T extends Number> {}
Run Code Online (Sandbox Code Playgroud)
问题是,我想接受T为Integer或Long,但不是Double.所以只有两个可接受的声明是:
MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
luk*_*uke 31
答案是不.至少没有办法使用泛型类型.我会建议使用泛型和工厂方法的组合来做你想要的.
class MyGenericClass<T extends Number> {
public static MyGenericClass<Long> newInstance(Long value) {
return new MyGenericClass<Long>(value);
}
public static MyGenericClass<Integer> newInstance(Integer value) {
return new MyGenericClass<Integer>(value);
}
// hide constructor so you have to use factory methods
private MyGenericClass(T value) {
// implement the constructor
}
// ... implement the class
public void frob(T number) {
// do something with T
}
}
Run Code Online (Sandbox Code Playgroud)
这确保了只能创建MyGenericClass<Integer>和MyGenericClass<Long>实例.虽然你仍然可以声明一个类型的变量,MyGenericClass<Double>但它只需要为null.