我想创建一个这种形式的通用类:
class MyGenericClass<T extends Number> {}
问题是,我希望 T 可以是 Integer 或 Long,但不能是 Double。因此,唯一可接受的两个声明是:
MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;
有什么办法可以做到这一点吗?
答案是不。至少没有办法使用泛型类型来做到这一点。我建议结合使用泛型和工厂方法来完成您想要的操作。
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
}
}
这确保了只有MyGenericClass<Integer>
and MyGenericClass<Long>
可以创建实例。尽管您仍然可以声明类型的变量MyGenericClass<Double>
它只需为空即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)