泛型和继承:需要一个复杂的Map实例

sp0*_*00m 4 java generics inheritance map

public abstract class Mother {
}

public class Daughter extends Mother {
}

public class Son extends Mother {
}
Run Code Online (Sandbox Code Playgroud)

我需要Map哪些键中的一个DaughterSon类,并且其值是这两个类中的一个,的对象列表分别.

例如:

/* 1. */ map.put(Daughter.class, new ArrayList<Daughter>()); // should compile
/* 2. */ map.put(Son.class, new ArrayList<Son>()); // should compile
/* 3. */ map.put(Daughter.class, new ArrayList<Son>()); // should not compile
/* 4. */ map.put(Son.class, new ArrayList<Daughter>()); // should not compile
Run Code Online (Sandbox Code Playgroud)

我试过了Map<Class<T extends Mother>, List<T>>,但它没有编译.

Map<Class<? extends Mother>, List<? extends Mother>>编译,但案例3.4.编译也是如此,但不应该.

它甚至可能吗?

Ian*_*rts 9

我不认为可以在类型中对此进行编码,我会使用自定义类进行编码

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

只要不泄漏backingMap此类之外的引用,就可以在此处禁止警告.