简体   繁体   中英

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:

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
    }

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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