gpt4 book ai didi

java - 为什么 & SomeInterface> 编译,而不是 >?

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:49 25 4
gpt4 key购买 nike

我不明白为什么 method2 不编译而 method1 编译。我将 Eclipse 与 JavaSE 1.7 一起使用,在方法 2 上出现以下错误:

Multiple markers at this line

  • The type Enum<T> is not an interface; it cannot be specified as a bounded parameter

  • Bound mismatch: The type T is not a valid substitute for the bounded parameter <E extends Enum<E>> of the type Enum<E>

public class Test {

public interface SomeInterface {

}

public static <T extends Enum<T> & SomeInterface> T method1() {
return null;
}

public static <T extends SomeInterface & Enum<T>> T method2() {
return null;
}
}

最佳答案

如果您查看 JLS 8.1.2 中类型参数边界的语法你会看到:

TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}

AdditionalBound:
& InterfaceType

换句话说,只有第一个指定的类型可以是一个类——所有其余的都必须是接口(interface)。

除此之外,这可以防止指定多个类。

它也反射(reflect)了声明类时的方式,您必须首先放置它正在扩展的类,然后是它实现的接口(interface) - 而不是相反。

关于java - 为什么 <T extends Enum<T> & SomeInterface> 编译,而不是 <T extends SomeInterface & Enum<T>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30194568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com