Java:混合泛型和 VarArgs
Java: Mixing Generics and VarArgs
我有以下定义特定类型的接口
public interface BaseInterface {
}
此接口将用于实现几个枚举,如:
public enum First implements BaseInterface {
A1, B1, C1;
}
public enum Second implements BaseInterface {
A2, B2, C2;
}
我现在想要一个有点像 Enum.valueOf(String) 的可重复使用的小方法,我的想法是我提供常量的名称以及可以实现它的所有可能类型。它将 return 实现接口的枚举对象(我不需要担心两个枚举常量具有相同名称的可能性)。客户端代码类似于:
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 类?
您需要使用以下定义:
@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
我有以下定义特定类型的接口
public interface BaseInterface {
}
此接口将用于实现几个枚举,如:
public enum First implements BaseInterface {
A1, B1, C1;
}
public enum Second implements BaseInterface {
A2, B2, C2;
}
我现在想要一个有点像 Enum.valueOf(String) 的可重复使用的小方法,我的想法是我提供常量的名称以及可以实现它的所有可能类型。它将 return 实现接口的枚举对象(我不需要担心两个枚举常量具有相同名称的可能性)。客户端代码类似于:
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 类?
您需要使用以下定义:
@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