与& - 操作员和订单的泛型含糊不清 [英] Generics ambiguity with the &-operator and order
问题描述
类中的3个方法:
pre> public static< E extends ClassA& ClassB的> void方法(E val){}
public static< E extends ClassC& ClassB& ClassA的> void方法(E val){}
public static< E extends ClassB> void method(E val){}
可以编译。
但是那些不是(歧义违反):
public static< E extends ClassA& ClassB的> void方法(E val){}
public static< E extends ClassB& ClassC& ClassA的> void方法(E val){}
public static< E extends ClassB> (ClassA,ClassB,ClassC)都是完全独立的(void)方法(E val){}
接口!)
由于类型擦除,编译器需要为参数选择静态已知类型键入编译的方法。
为此,它使用约束列表中的第一个类型。
在你的第一个例子中,这导致每种方法都有一个唯一的类型,所以它编译为
public static method(ClassA val) ;
公共静态方法(ClassC val);
公共静态方法(ClassB val);
这是完全合法的(除了你的遗漏类型)。它会创建三种不同的参数类型的重载。
在第二个示例中,这会产生一个不明确的含义:
public static method(ClassA val);
公共静态方法(ClassB val);
公共静态方法(ClassB val);
这是不合法的,因为最后两个方法具有相同的签名。
试图从每个重载中选择一个约束类型使其没有冲突,这可能是合法的,但这会很复杂&安培;缓慢的更大的约束列表。
规格可能有如下所示:
如果它用于擦除参数列表中的一个类型,选择泛型方法中类型变量的擦除,使得该方法的每个重载都会导致擦除后的唯一签名。
如果没有擦除组合会导致
我怀疑这个问题出现在NP中。
I have a strange Java generics ambiguity behaviour that I cannot explain:
Those 3 methods in class:
public static <E extends ClassA & ClassB> void method(E val) {}
public static <E extends ClassC & ClassB & ClassA> void method(E val) {}
public static <E extends ClassB> void method(E val) {}
compile fine.
But those not (ambiguity violation):
public static <E extends ClassA & ClassB> void method(E val) {}
public static <E extends ClassB & ClassC & ClassA> void method(E val) {}
public static <E extends ClassB> void method(E val) {}
(ClassA, ClassB, ClassC are all completely independent interfaces!)
Due to type erasure, the compiler needs to pick a statically-known type for the parameter type in the compiled method.
To do this, it uses the first type in your constraint list.
In your first example, this results in a unique type for each method, so it compiles to
public static method(ClassA val);
public static method(ClassC val);
public static method(ClassB val);
This is perfectly legal (except for your missing return type); it creates three overloads with three different parameter types.
In your second example, this creates an ambiguity:
public static method(ClassA val);
public static method(ClassB val);
public static method(ClassB val);
This is not legal, because the last two methods have the same signature.
The spec explicitly documents this behavior.
This could have been made legal by trying to pick a single constraint type from each overload such that there are no conflicts, but that would be complicated & slow for larger constraint lists.
The spec could have said something like:
If it is used in erasure of a type in the parameter list, the erasure of a type variable in a generic method is chosen such that each overload of that method results in a unique signature after erasure.
If no combination of erasures will result in a unique signature, an ambiguity error occurs.
I suspect that this problem is in NP.
这篇关于与& - 操作员和订单的泛型含糊不清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!