今天,我尝试编写一个具有使用交集类型的泛型方法的类,但根据交集类型的不同错误消息而感到困惑。假设我们有一个interface
and a class
并在通用接口中定义通用方法:
class ClassType {
}
interface InterfaceType {
}
interface I<T> {
public <X extends InterfaceType & InterfaceType> void foo();
public <X extends ClassType & ClassType> void foo1();
public <X extends ClassType & InterfaceType> void foo2();
public <X extends InterfaceType & ClassType> void foo3();
public <X extends T & ClassType> void foo4();
public <X extends ClassType & T> void foo5();
public <X extends InterfaceType & T> void foo6();
public <X extends T & InterfaceType> void foo7();
}
编译此方法会对除以下方法之外的所有方法产生错误public <X extends ClassType & InterfaceType> void foo2();
.
Main.java:8: error: repeated interface
public <X extends InterfaceType & InterfaceType> void foo();
^
Main.java:10: error: interface expected here
public <X extends ClassType & ClassType> void foo1();
^
Main.java:14: error: interface expected here
public <X extends InterfaceType & ClassType> void foo3();
^
Main.java:16: error: a type variable may not be followed by other bounds
public <X extends T & ClassType> void foo4();
^
Main.java:18: error: unexpected type
public <X extends ClassType & T> void foo5();
^
required: class
found: type parameter T
where T is a type-variable:
T extends Object declared in interface I
Main.java:20: error: unexpected type
public <X extends InterfaceType & T> void foo6();
^
required: class
found: type parameter T
where T is a type-variable:
T extends Object declared in interface I
Main.java:22: error: a type variable may not be followed by other bounds
public <X extends T & InterfaceType> void foo7();
^
7 errors
由于交叉点应该是对称的,我很惊讶foo2
被接受但是foo3
被拒绝。为什么这一案例会被受理?
我还想知道为什么在交集类型方面接口、类和类型参数之间存在区别。我可以看到不允许交叉类型中存在多个类的原因,但当前状态接受ClassType & InterfaceType
但不是InterfaceType & ClassType
似乎很随意。一个十字路口A & A
也是被禁止的,但这在语义上与A
所以我不认为这是有原因的。
我也很好奇为什么类型变量不允许出现在交集中。最坏的情况是两个或多个类的交集,但只是无人居住的类型,因此是底部类型。
你只能有 1 个类,但有多个接口。如果您有一个类,它必须是第一个指定的类。如果遵循此规则,则不应出现任何编译错误。
See https://docs.oracle.com/javase/tutorial/java/generics/bounded.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)