Generics and inheritance: need a complex Map instance

前端 未结 2 1750
盖世英雄少女心
盖世英雄少女心 2020-12-06 20:43
public abstract class Mother {
}

public class Daughter extends Mother {
}

public class Son extends Mother {
}

相关标签:
2条回答
  • 2020-12-06 21:39

    I don't think it's possible to encode this in the type, I'd do it with a custom class

    class ClassMap<T> {
      private Map<Class<? extends T>, List<? extends T>> backingMap = new HashMap<>();
    
      public <E extends T> void put(Class<E> cls, List<E> value) {
        backingMap.put(cls, value);
      }
    
      @SuppressWarnings("unchecked")
      public <E extends T> List<E> get(Class<E> cls) {
        return (List<E>)backingMap.get(cls);
      }
    }
    

    It's safe to suppress warnings here as long as you don't leak the backingMap reference outside this class.

    0 讨论(0)
  • 2020-12-06 21:40

    Assuming you're looking for a single map, no this is not possible.

    0 讨论(0)
提交回复
热议问题