Got some problem when using Generic with Enum:
enum MyEnum1 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}
enum MyEnum2 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}
enum MyEnum3 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}
class MyClass {
Map<Class<? extends Enum<?>, EnumSet<? extends Enum<?>>> map;
public <E extends Enum<E>> void addValue2EnumSet(Class<E> enumType, E value);
// enumType and valueStr is of the same length
public static Map<Class<? extends Enum<?>, EnumSet<? extends Enum<?>>> getMapOfEnumSet(Class<? extends Enum<?>>[] enumTypes, String[] valueStrs) {
for (int i = 0; i < enumTypes.length; ++i) {
// for each enumType and valueStr pair
// add the value from valueStr to the Map
Class<? extends Enum<?>> enumType = enumTypes[i];
String valueStr = valueStrs[i];
MyClass c = // ...
Method fromStringMethod = enumType.getDeclaredMethod("fromString", String.class);
c.addValue2EnumSet(enumType, enumType.cast(fromStringMethod.invoke(null, valueStr))); // error!
}
return c.map;
}
}
In this line c.addValue2EnumSet(enumType, enumType(fromStringMethod.invoke(null, valueStr)));
, an compile-error is the second parameter, Found: 'java.lang.Enum<?>
, required: '? extends java.lang.Enum'`
How to call addValue2EnumSet()
in getEnumSetOf()
?
In this case, a Class<? extends Enum<?> enumType
parameter is passed, and it is used to judge which kind of Enum (Enum1/2/3) is the target, then call the fromString()
method to generate the corresponding Enum instance. I have no idea but the reflection to get methods from the enumType.
Aucun commentaire:
Enregistrer un commentaire