【问题标题】:Static field with generic parameter extending multiple types具有扩展多种类型的泛型参数的静态字段
【发布时间】:2016-08-12 17:23:30
【问题描述】:

我没有任何问题:

我有多个扩展同一个接口的枚举:

interface CommonMethods {
    // some methods
}

enum E1 implements CommonMethods {
    O1, O2;
    // interface method impls
}

enum E2 implements CommonMethods {
    O3, O4;
    // interface method impls
}

我想通过他们的共同继任者来处理这些问题:EnumCommonMethods

到目前为止,我有这样的方法:

static <L extends Enum<?> & CommonMethods> void m(L l) {}

所以我可以对这些枚举做我想做的事情,例如通过从 CommonMethods 接口调用方法。

现在问题开始了:

但我也想将其中一些存储在这样的类的静态列表字段中:

class Test1 {
    static List<Enum<?> & CommonMethods> l = new LinkedList<>();

    static {
        l.add(E1.O1);
        l.add(E2.O3);
    }
}

这给了我编译器错误。我有一个我认为不好的解决方法:

class Test2 {
    static List<Enum<?>> l = new LinkedList<>();

    static {
        l.add(E1.O1);
        l.add(E2.O3);
    }

    static <L extends Enum<?> & CommonMethods> void m(L l) {}
}

这样我就失去了可接受类型的约束。


我可以做些什么来保持约束?

注意:这只是一个虚拟代码,而不是我目前正在尝试使用的真实代码,因此请不要重构建议。

【问题讨论】:

    标签: java generics enums multiple-bounds


    【解决方案1】:

    将类型声明为:

    static <L extends Enum<? extends CommonMethods>> void m(L l) {}
    

    我自己在进行大量研究之前和之后都遇到过这个问题,我得出的结论是这与类型交集的效果相同。

    这个question 及其答案讨论了这个话题。

    【讨论】:

    • 我想你的意思是:static &lt;L extends Enum&lt;? extends CommonMethods&gt;&gt; void m(L l) {}。我说的对吗?
    • @Bart 我认为你是对的。有关此主题的讨论,请参阅this question
    • 接口没有参数化怎么办?
    • @basin 接口CommonMethods 未参数化。该问题询问参数化enum
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多