简体   繁体   English

无法找出HashMap的正确类型

[英]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();
  ...
}

now i want to use this construct typesave, i got this: 现在我想使用这个构造typesave,我得到了这个:

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. 这似乎是正确的,clazz应该只在上面的枚举工作。 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 这里有一些pastebin: https//pastebin.com/fKxtBGBe


EDIT 1: 编辑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
    }

Type erasure... provide the type object of the generic type parameter. 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);

This also decouples the implementation type (EnumA). 这也解耦了实现类型(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. 如果需要,将类型转换为Enum。

If you wish to create a map of a sting to a class, this should work for you : 如果你想创建一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM