的泛型类我想打一个泛型类这种形式:接受以下两种类型
class MyGenericClass<T extends Number> {}
问题是,我想是可以接受的对于T是整数或长,但不增加一倍。因此,只有两个可以接受的声明将是:
MyGenericClass<Integer> instance;
MyGenericClass<Long> instance;
有没有办法做到这一点?
的泛型类我想打一个泛型类这种形式:接受以下两种类型
class MyGenericClass<T extends Number> {}
问题是,我想是可以接受的对于T是整数或长,但不增加一倍。因此,只有两个可以接受的声明将是:
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>
和MyGenericClass<Long>
实例可以被创建。尽管您仍然可以声明MyGenericClass<Double>
类型的变量,但它必须为空。
不,Java泛型没有任何东西允许这样做。您可能要考虑拥有一个非通用接口,由FooIntegerImpl
和FooLongImpl
执行。如果不知道更多关于你想要达到的目标,很难说。
那么使用泛型的好处在哪里呢?由于使参数类型为T的方法可以接受任何数字? – 2012-02-04 16:15:55
在你的代码中,它绝对不是。由于不能写入方法接受类型T的参数。您必须为每个此类方法编写两个单独的定义,一个用于Integer,另一个用于Long。 – 2012-02-04 16:29:37
@djaqeel这不是事实。如果您尝试将frob方法与Long或整数以外的其他方法一起使用,您将得到一个编译器异常。 – luke 2012-02-04 17:36:45