接受两种类型之一的generics类
我想创建一个这种forms的generics类:
class MyGenericClass {}
问题是,我想接受T为Integer或Long,但不是Double。 所以只有两个可接受的声明是:
MyGenericClass instance; MyGenericClass instance;
有没有办法做到这一点?
答案是不。 至少没有办法使用generics类型。 我建议结合使用generics和工厂方法来做你想做的事。
class MyGenericClass { public static MyGenericClass newInstance(Long value) { return new MyGenericClass (value); } public static MyGenericClass newInstance(Integer value) { return new MyGenericClass (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
和MyGenericClass
实例。 虽然您仍然可以声明MyGenericClass
类型的变量,但它必须为null。
不,Javagenerics中没有任何内容允许这样做。 您可能需要考虑使用由FooIntegerImpl
和FooLongImpl
实现的非generics接口。 如果不了解更多关于你想要实现的目标,很难说。