Java – Unable to find out the correct type of HashMap

Unable to find out the correct type of HashMap… here is a solution to the problem.

Unable to find out the correct type of 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 save with this constructor type and 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, clazz should only work for the above enumeration. But right now, I can’t figure out the correct type of map, it won’t work :

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

Does anyone know? I want this thing type to be safe.

Here are some pastebin: https://pastebin.com/fKxtBGBe


Edit 1:

Tried something similar 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
    }

Solution

Type Delete… A type object that provides generic type parameters.

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 seek partial type security

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()) {
        ....
    }
}

If needed, convert the type to an enumeration.

Related Problems and Solutions