今天,我尝试编写一个具有通用方法的类,该方法使用交集类型,但对取决于交集类型的不同错误消息感到困惑。假设我们有一个 interface
和一个 class
并在通用接口(interface)中定义通用方法:
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
被拒绝了。为什么这个案例被接受?
我也想知道为什么在涉及交集类型时接口(interface)、类和类型参数之间存在区别。我可以看到在交叉类型中不允许超过一个类的原因,但当前状态接受 ClassType & InterfaceType
但不是 InterfaceType & ClassType
似乎很随意。一个路口A & A
也被禁止,但这在语义上等同于 A
所以我看不出这是什么原因。
我也很好奇为什么交集里不允许类型变量。最坏的情况是两个或多个类的交集,但只是一个无人居住的类型,因此是底层类型。
最佳答案
你只能有 1 个类,但有多个接口(interface)。如果你有一个类,它必须是第一个指定的。如果您遵循此规则,则不应出现任何编译错误。
参见 https://docs.oracle.com/javase/tutorial/java/generics/bounded.html
关于java - Java 交集类型与接口(interface)类和类型变量的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912276/