实例化作为参数传递的类的枚举

pio*_*rek -1 java generics enums compiler-warnings

我有一个方法:

public Object instantiateAlmostAnyType(String stringToParse, Class<?> targetType) {
  ...
  if (targetType.isEnum())
    return Enum.valueOf((Class)targetType, stringToParse);
}
Run Code Online (Sandbox Code Playgroud)

它工作,但我有编译器警告.所有的return线:

Class is a raw type. References to generic type Class should be parameterized
Enum is a raw type. References to generic type Enum should be parameterized
Type safety: The expression of type Class needs unchecked conversion to conform to Class
Type safety: Unchecked invocation valueOf(Class, String) of the generic method valueOf(Class, String) of type Enum

是否有任何方法(@suppressWarnings除外)以避免警告?任何演员?

Ste*_*ker 5

public <T extends Enum<T>> T instantiate(String stringToParse, Class<T> targetType) {
    ...
    return Enum.valueOf(targetType, stringToParse);
}
Run Code Online (Sandbox Code Playgroud)

现在,您在编译时检查Class实例必须是一个enum类型,并且不必执行任何不安全的转换.