Reputation: 51
filter.put("a", EnumA.class);I got following setup:
public interface InterfaceA {
abstract public Object[] foo();
}
public enum EnumA implements InterfaceA {
RED();
...
}
public enum EnumB implements InterfaceA {
OAK();
...
}
now i want to use this construct typesave, i got this:
private <T extends Enum<T> & InterfaceA> void importSettingViaEnum(Class<T> clazz) { ...
for (T elem : clazz.getEnumConstants()){
... = f(elem.ordinal());
... = elem.foo();
...
}
}
this seems to be correct, the clazz should only work work the enums above. But now, i can't figure out the correct type of this map, this is not working:
public <T extends Enum<T> & InterfaceA> Main() {
Map<String, Class<T>> filter = new HashMap<>();
filter.put("a", EnumA.class);
filter.put("b", EnumB.class);
importSettingViaEnum(filter.get("a"));
}
Someone has a clue ? I wish to have this thing typesafe.
Here some pastebin: https://pastebin.com/fKxtBGBe
EDIT 1:
Tried something like this, but it won't work...
public Main() {
Map<String, Class<? extends Enum<? extends InterfaceA>>> filter = new HashMap<>();
filter.put("a", EnumA.class);
filter.put("b", EnumB.class);
importSettingViaEnum(filter.get("a")); // BREAK THE BUILD
}
Upvotes: 3
Views: 96
Reputation: 109547
Type erasure... provide the type object of the generic type parameter.
public <T extends Enum<T> & InterfaceA> void main(Class<T> type) {
Map<String, Class<T>> filter = new HashMap<>();
filter.put("a", type);
//importSettingViaEnum(filter.get("a"));
}
main(EnumA.class);
This also decouples the implementation type (EnumA).
Or go for partial type safeness
public void main2() {
Map<String, Class<? extends InterfaceA>> filter = new HashMap<>();
filter.put("a", EnumA.class);
Class<? extends InterfaceA> type = filter.get("a");
if (type.isEnum()) {
....
}
}
Cast type to Enum if needed.
Upvotes: 3
Reputation: 31878
If you wish to create a map of a sting to a class, this should work for you :
Map<String, Class> filter = new HashMap<>(); // any Class put against a string in the map
filter.put("a", EnumA.class);
Upvotes: 0