首页 > 解决方案 > 带有泛型参数接口的回调

问题描述

我有一个通用容器接口,用于SparseArray在 Java 代码中抽象出 Android:

public interface MyContainer<T> {
    T get(int key);
    void forEach(Consumer<T> consumer);
}

我有一个带有 容器的类Implementation,但我只想在Interface外部公开:

MyContainer<Implementation> data;
Interface get(int key) {
    return data.get(key);
}
void method(Consumer<Interface> callback) {
   data.forEach(callback); //here
}

但我得到一个编译器错误:

error: incompatible types: Consumer<Interface> cannot be converted to Consumer<Implementation>

如何更改MyContainer接口以允许Consumer<Interface>传递给我的班级?

标签: javagenerics

解决方案


MyContainer中,Consumer的类型参数可以具有T下限。

void forEach(Consumer<? super T> consumer);

这样,消耗超类型的东西T可以作为参数传入。

对于Consumer自身,如果它可以处理 的超类型T,那么它也可以处理 a T。这是 PECS 的一部分 - 生产者扩展,消费者超级。

然后,在 中method,您可以将 a 传递Consumer<Interface>forEach。这里,TImplementation。该类型Interface是 的超类型Implementation,因此下限允许这样做。


推荐阅读