java - Java 交集类型与接口(interface)类和类型变量的限制

标签 java types jls

今天,我尝试编写一个具有通用方法的类,该方法使用交集类型,但对取决于交集类型的不同错误消息感到困惑。假设我们有一个 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/

相关文章:

java - Azure + SpringBoot 'com/fasterxml/jackson/core/JsonFactory'

java - 防止 play2.1 应用程序同时发生数据库事务

c# - 如何定义 "Type"的含义

java - Java 中的字符串池的行为是否类似于 LRU 缓存?

java - JLS 的哪些部分证明能够像未经检查一样抛出已检查异常?

java - 在 EmployeePanel NurseRoster 中显示假期的建议方法

java - 以下代码中的文件IO疑问

java - 检查方法返回值的类型

Python 检查整数输入

java - JVM 尖括号中的标识符导致内部方法错误