我有以下泛型类:
- class Or<A,B>
- {
- Or (A a) {}
- Or (B b) {}
- }
我尝试编译时为什么会出现以下错误:
- Or(A) is already defined in Or
- Or (B b)
- ^
在我看来,两个构造函数共享相同的签名,尽管它们具有不同的泛型类型参数.为什么?以及如何解决这个问题?
更新
我现在明白了这个问题.编译器需要一种方法来区分这两种类型.添加这样的约束对我的用例来说是可以的.所以我想补充一个问题:
如何指定A和B这两种类型可能是不同的?
解决方法
It seems to me that the two constructors share the same signature although they have different generic type arguments.
他们是这样.签名是
- Or(Object o);
Why?
由于Java中7000泛型的实现:对泛型类型的引用在使用它们的所有上下文中都被转换为System.Object;泛型类型只有编译器知道.
And how to work around this problem?
不幸的是,您无法在构造函数中轻松解决此问题.您可以使用工厂方法替换重载的构造函数,并提供不同的名称,例如OrWithA和OrWithB:
- // Hide the constructor
- private Or(...) {
- ...
- }
- // Publish factory methods
- public static <X> Or OrWithA(X a) {
- return new Or(...);
- }
- public static <X> Or OrWithB(X a) {
- return new Or(...);
- }