首页 文章

Java:混合泛型和VarArgs

提问于
浏览
0

我有以下界面定义了某种类型

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?

1 回答

  • 3

    您需要使用以下定义:

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

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

相关问题