为什么 <T extends Enum<T> 和 Some Interface> 编译,而不是 <T extends SomeInterface & Enum<T>>?
Why does <T extends Enum<T> & SomeInterface> compile, but not <T extends SomeInterface & Enum<T>>?
我不明白为什么 method2 不编译而 method1 编译。
我在 JavaSE 1.7 中使用 Eclipse,在 method2 上出现以下错误:
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
换句话说,只有第一个指定的类型可以是class - 其余的都必须是接口。
除此之外,这可以防止指定多个 classes。
它也反映了声明 class 时的方式,您必须先放置它正在扩展的 class,然后是它实现的接口 - 而不是相反。
根据 docs:
A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:
Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }
class D <T extends A & B & C> { /* ... */ }
If bound A is not specified first, you get a compile-time error:
class D <T extends B & A & C> { /* ... */ } // compile-time error
由于在您的示例中 method2
首先具有接口 SomeInterface
,因此它显示编译器错误
我不明白为什么 method2 不编译而 method1 编译。 我在 JavaSE 1.7 中使用 Eclipse,在 method2 上出现以下错误:
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
换句话说,只有第一个指定的类型可以是class - 其余的都必须是接口。
除此之外,这可以防止指定多个 classes。
它也反映了声明 class 时的方式,您必须先放置它正在扩展的 class,然后是它实现的接口 - 而不是相反。
根据 docs:
A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:
Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }
class D <T extends A & B & C> { /* ... */ }
If bound A is not specified first, you get a compile-time error:
class D <T extends B & A & C> { /* ... */ } // compile-time error
由于在您的示例中 method2
首先具有接口 SomeInterface
,因此它显示编译器错误