具有通用参数接口的回调

时间:2019-03-19 21:13:14

标签: java generics

我有一个通用的容器接口,可用于用Java代码提取Android SparseArray

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>传递给我的班级?

1 个答案:

答案 0 :(得分:6)

MyContainer中,Consumer的type参数可以将T作为下限。

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

这样,可以将使用T超型的内容作为参数传递。

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

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