[英]Can't figure out the correct type for a HashMap
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();
...
}
现在我想使用这个构造typesave,我得到了这个:
private <T extends Enum<T> & InterfaceA> void importSettingViaEnum(Class<T> clazz) { ...
for (T elem : clazz.getEnumConstants()){
... = f(elem.ordinal());
... = elem.foo();
...
}
}
这似乎是正确的,clazz应该只在上面的枚举工作。 但现在,我无法弄清楚这张地图的正确类型,这是行不通的:
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"));
}
有人有线索吗? 我希望这个东西是类型安全的。
这里有一些pastebin: https : //pastebin.com/fKxtBGBe
编辑1:
尝试过类似的东西,但它不会起作用......
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
}
Type erasure ...提供泛型类型参数的类型对象。
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);
这也解耦了实现类型(EnumA)。
或者选择部分类型安全
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()) {
....
}
}
如果需要,将类型转换为Enum。
如果你想创建一个sting到一个类的地图,这应该适合你:
Map<String, Class> filter = new HashMap<>(); // any Class put against a string in the map
filter.put("a", EnumA.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.