Luc*_*ZAN 11 java generics enums type-bounds
我无法理解为什么method2不编译而method1编译.我在JavaSE 1.7中使用Eclipse,我在method2上遇到以下错误:
此行有多个标记
Enum <T>类型不是接口; 它不能指定为有界参数
绑定不匹配:类型T不是Enum <E>类型的有界参数<E extends 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;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 16
如果你看一下JLS 8.1.2中类型参数边界的语法,你会看到:
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
AdditionalBound:
& InterfaceType
Run Code Online (Sandbox Code Playgroud)
换句话说,只有指定的第一个类型可以是一个类 - 其余的都必须是接口.
除了其他任何东西,这可以防止指定多个类.
它还反映了在声明一个类时,你必须首先将它扩展的类,然后是它实现的接口 - 而不是反过来.
根据文件:
具有多个边界的类型变量是绑定中列出的所有类型的子类型.如果其中一个边界是类,则必须首先指定它.例如:
Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }
class D <T extends A & B & C> { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
如果未首先指定绑定A,则会出现编译时错误:
class D <T extends B & A & C> { /* ... */ } // compile-time error
Run Code Online (Sandbox Code Playgroud)
由于在您的示例method2中SomeInterface首先具有接口,因此它显示编译器错误