This is similar, but not quite the same as Java: instantiating using reflection
I have a Map<Enum<?>, FooHandler> , which I want to use to display Enum (I don't care what type or even if they are of the same type, as long as they are enumeration constants) to my FooHandler class.
I would like to fill out this card using a text file that I read. I can make it work, but I have two warnings that I would like to get around:
static private <E extends Enum<E>> E getEnum(String enumFullName) { // see https://stackoverflow.com/questions/4545937/ String[] x = enumFullName.split("\\.(?=[^\\.]+$)"); if (x.length == 2) { String enumClassName = x[0]; String enumName = x[1]; try { Class<E> cl = (Class<E>)Class.forName(enumClassName); //
Warning # 1: Unchecking Warning # 2: Enum is a raw type.
I get # 1 and can just put a warning, I suppose, but it seems like I can't beat warning # 2; I tried Enum<?> And it just gives me an error about a generic type binding mismatch.
Alternative implementations that are worse: Until my return value <E extends Enum<E>> I tried to return Enum, and this did not work; I received these warnings / errors:
static private Enum<?> getEnum(String enumFullName) { ... Class<?> cl = (Class<?>)Class.forName(enumClassName);
and this:
static private Enum<?> getEnum(String enumFullName) { ... Class<Enum<?>> cl = (Class<Enum<?>>)Class.forName(enumClassName); // 1 return Enum.valueOf(cl, enumName); // 2
- warning:
Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum<?>> - error:
Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<Enum<?>>, String). The inferred type Enum<?> is not a valid substitute for the bounded parameter <T extends Enum<T>> Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<Enum<?>>, String). The inferred type Enum<?> is not a valid substitute for the bounded parameter <T extends Enum<T>>
java reflection enums
Jason s
source share