Java通用功能无法编译:需要接口类型

发布于 2025-02-11 16:49:16 字数 711 浏览 2 评论 0原文

我正在尝试“有效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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离不开的别离 2025-02-18 16:49:16

在使用&amp;/code>中时,只有第一部分可以是类。其他一切都必须是接口。 操作不是接口,这就是为什么失败的原因。

但是您的榜样毫无意义。只有一种匹配t的类型扩展了枚举&lt; t&gt; &amp;操作,那是操作本身。为什么还是要使用通用类型?

以下内容是可能的(是的,操作Enum是一个可怕的名称):

interface Operation { /* some methods */ }
enum OperationEnum implements Operation { /* constants, methods from Operation */ }

但是,除非您定义了一个实际添加枚举中尚未在枚举中的界面(例如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's Operation itself. Why use a generic type anyway?

The following would be possible (yes, OperationEnum is a terrible name):

interface Operation { /* some methods */ }
enum OperationEnum implements Operation { /* constants, methods from Operation */ }

But unless you define an interface that actually adds methods that aren't already in enums (like name() and ordinal()), there's no need to use a stronger bound than just T extends Enum<T>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文