Java通用功能无法编译:需要接口类型
我正在尝试“有效Java,项目34”中的示例代码段。我在Win10上使用JDK1.8。
package mygroup;
import java.util.*;
public class ExtendsEnum {
private static enum Operation {
Plus,
Minus;
}
public static <T extends Enum<T> & Operation> // error
void testEnumClass(Class<T> opSet) {
for (Operation op : opSet.getEnumConstants()) {
System.out.println(op);
}
}
public static void main(String[] args) {
ExtendsEnum.testEnumClass(Operation.class);
}
}
编译器说:需要接口类型。 我不确定问题行上的程序是否在JDK1.8中仍然有效,我只是尝试从书的示例代码中复制。 JDK是否会识别:
<T extends Enum<T> & Operation>
如果没有,如何修复它?
I'm trying a sample code snippet from "Effective Java, item 34". I'm using jdk1.8 on win10.
package mygroup;
import java.util.*;
public class ExtendsEnum {
private static enum Operation {
Plus,
Minus;
}
public static <T extends Enum<T> & Operation> // error
void testEnumClass(Class<T> opSet) {
for (Operation op : opSet.getEnumConstants()) {
System.out.println(op);
}
}
public static void main(String[] args) {
ExtendsEnum.testEnumClass(Operation.class);
}
}
Compiler says: needs interface type.
I'm not sure if my program on the problem line is still valid in jdk1.8, I just tried to copy from the book's sample code.
Does jdk recognize:
<T extends Enum<T> & Operation>
If not, how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在使用
&amp;/code>中时,只有第一部分可以是类。其他一切都必须是接口。
操作
不是接口,这就是为什么失败的原因。但是您的榜样毫无意义。只有一种匹配
t的类型扩展了枚举&lt; t&gt; &amp;操作
,那是操作
本身。为什么还是要使用通用类型?以下内容是可能的(是的,
操作Enum
是一个可怕的名称):但是,除非您定义了一个实际添加枚举中尚未在枚举中的界面(例如
name() and
ordinal()
),不需要使用更强的界限,而不是t扩展了枚举&lt; t&gt;
。When using
&
in generic bounds, only the first part may be a class. Everything else must be an interface.Operation
isn't an interface, that's why it fails.But your example makes no sense. There is only one type that matches
T extends Enum<T> & Operation
, and that'sOperation
itself. Why use a generic type anyway?The following would be possible (yes,
OperationEnum
is a terrible name):But unless you define an interface that actually adds methods that aren't already in enums (like
name()
andordinal()
), there's no need to use a stronger bound than justT extends Enum<T>
.