使用Java泛型使两种类型相同

时间:2020-02-13 04:17:50

标签: java generics

请考虑以下内容:

public interface Sendable<T> { T details() }
public interface Receiver<T> { void receive(T details) }

我想从任何类型的Sendable到相同类型的Receiver进行映射。它们必须是相同的类型,因为有时我想打电话给

receiver.receive(sendable.details());

,否则编译器将拒绝它。我计划发送许多类型。我可以做类似的事情:

public class Foo {
  Map<Sendable<Integer>, Receiver<Integer>> intmap;
  Map<Sendable<String>, Receiver<String>> stringmap;
  ... 
  //put a map for each type
}

,但是每次我想发送一些新类型时,我都必须更新此类。我想做类似的事情

public class Foo {
  Map<Sendable<?>, Receiver<?>> map;
}

因为我只需要编写一次并永久使用它,但这显然是行不通的,因为?不是一个 ?。那么,如何为任何T绘制从T到T的地图?

无需强制转换,可以克服静态键入的问题。

0 个答案:

没有答案
相关问题