2012-02-04 64 views
21

的泛型类我想打一个泛型类这种形式:接受以下两种类型

class MyGenericClass<T extends Number> {} 

问题是,我想是可以接受的对于T是整数或长,但不增加一倍。因此,只有两个可以接受的声明将是:

MyGenericClass<Integer> instance; 
MyGenericClass<Long> instance; 

有没有办法做到这一点?

回答

22

答案是否定的。至少没有办法使用泛型类型来完成它。我会推荐泛型和工厂方法的组合来做你想做的事情。

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>类型的变量,但它必须为空。

+0

那么使用泛型的好处在哪里呢?由于使参数类型为T的方法可以接受任何数字? – 2012-02-04 16:15:55

+0

在你的代码中,它绝对不是。由于不能写入方法接受类型T的参数。您必须为每个此类方法编写两个单独的定义,一个用于Integer,另一个用于Long。 – 2012-02-04 16:29:37

+0

@djaqeel这不是事实。如果您尝试将frob方法与Long或整数以外的其他方法一起使用,您将得到一个编译器异常。 – luke 2012-02-04 17:36:45

2

不,Java泛型没有任何东西允许这样做。您可能要考虑拥有一个非通用接口,由FooIntegerImplFooLongImpl执行。如果不知道更多关于你想要达到的目标,很难说。

+0

我想到了这一点,它会解决我的问题。我只是想知道,如果Java泛型允许我做到这一点,而不必声明这个类。但我不会使用接口,因为这两个类的实现是相同的。我将创建一个抽象包保护类,并创建两个公共类来扩展它。 – Rafael 2012-02-04 15:54:12

+0

至于我想实现的目标,我想创建一个对Integer,Long或任何其他类似int的类型有意义的类,但将它与浮点类型一起使用是没有意义的。 – Rafael 2012-02-04 15:57:23

相关问题