【问题标题】:Java: Mixing Generics and VarArgsJava:混合泛型和 VarArgs
【发布时间】:2016-10-03 16:24:15
【问题描述】:

我有以下定义某种类型的接口

public interface BaseInterface {
}

这个接口将用于实现几个枚举,如:

public enum First implements BaseInterface {
  A1, B1, C1;
}


public enum Second implements BaseInterface {
  A2, B2, C2;
}

我现在想要一个工作起来有点像 Enum.valueOf(String) 的小型可重用方法,我的想法是我提供一个常量的名称以及可以实现它的所有可能类型。它将返回实现接口的枚举对象(我不需要担心两个枚举常量同名的可能性)。客户端代码如下所示:

BaseInterface myConstant = parse("A1", First.class, Second.class);

我卡住的地方是方法的定义。我当时在想一些事情:

@SafeVarargs
private final <T extends Enum<T> & BaseInterface > T parse(String name, Class<T>... types) {
    // add code here
}

然而,Java 编译器抱怨types 的定义。它只会让我通过一种独特的类型!以下是有效的:

parse("A1");
parse("A1", First.class);
parse("A1", First.class, First.class);
parse("A1", First.class, First.class, First.class);
parse("A1", Second.class);
parse("A1", Second.class, Second.class);

但有用的版本不是:

parse("A1", First.class, Second.class);

我如何告诉 Java types 可以采用扩展 Enum 并实现 BaseInterface 的 ALL 类?

【问题讨论】:

  • Enum 扩展BaesInterface 并仅使用BaseInterface
  • 这是可以理解的,因为您的声明中所说的types 将包含单一类型T 的元素,它必须既是枚举又是BaseInterface

标签: java generics enums interface variadic-functions


【解决方案1】:

您需要使用以下定义:

@SafeVarargs
private static final <T extends Enum<?> & BaseInterface> T parse(String name, Class<? extends T>... types) {
    // add code here
}

&lt;? extends T&gt; 允许编译器推断出比您传递的特定类型更通用的类型,? extends Enum&lt;?&gt;T 成为任何通用枚举类型,而不是一个特定的枚举 T

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 2011-08-16
    • 2015-11-04
    • 2012-09-13
    • 1970-01-01
    • 2017-12-24
    • 2021-12-15
    • 2011-04-25
    相关资源
    最近更新 更多