未检查泛型类的类型转换?(Unchecked typecasting of generic class?)

我正在尝试编写一个方法,我可以在运行时将字符串转换为枚举对象,用于通用枚举。 我有一个方法签名:

public static <T extends Enum<T>> Enum<T> foo(String string, Class<T> clazz)

不过,我从一个泛型类型参数没有明确扩展Enum的类调用它。 即

class bar<X> { private Class<X> clazz; if (XIsAnEnum()) { foo(string, clazz) } }

这不能编译,因为即使我知道,从XIsAnEnum的逻辑中, X extends Enum<X> ,我没有在泛型类型参数定义中明确说明这一点,所以它不是一个有效的参数。

有没有办法从Class<X>到Class<X extends Enum<X>>进行未经检查的强制转换,或者我必须创建一个新类bar2<X extends Enum<X>>专门用于我想要使用的时候枚举?

I am trying to write a method where I can convert from a string to an enum object at runtime, for a generic enum. I have a method signature:

public static <T extends Enum<T>> Enum<T> foo(String string, Class<T> clazz)

However, I am calling it from a class whose generic type parameter does not explicitly extend Enum. i.e.

class bar<X> { private Class<X> clazz; if (XIsAnEnum()) { foo(string, clazz) } }

This does not compile because even though I know, from the logic of XIsAnEnum, that X extends Enum<X>, I don't explicitly state this in the generic type parameter definition, so it is not a valid argument.

Is there a way to do an unchecked cast from Class<X> to Class<X extends Enum<X>>, or will I have to make a new class bar2<X extends Enum<X>> specifically for when I want to use enums?

最满意答案

你可以使用Class#asSubclass(Class)为你做演员表,比如

foo("value", clazz.asSubclass(Enum.class));

这涉及一个实际的验证, clazz指的是Enum一个子类。

尽管你在这里抛出所有的通用验证。

You can use Class#asSubclass(Class) to do the cast for you, like

foo("value", clazz.asSubclass(Enum.class));

This involves an actual verification that clazz is referring to a Class that is a subclass of Enum.

You're throwing out all the generic verification here though.

更多推荐