具有通用参数接口的回调

Moo*_*uck 2 java generics

我有一个通用的容器接口,可用于以SparseArrayJava代码抽象出Android :

public interface MyContainer<T> {
    T get(int key);
    void forEach(Consumer<T> consumer);
}
Run Code Online (Sandbox Code Playgroud)

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

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

但是我遇到了编译器错误:

error: incompatible types: Consumer<Interface> cannot be converted to Consumer<Implementation>
Run Code Online (Sandbox Code Playgroud)

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

rge*_*man 6

在中MyContainerConsumer类型参数可以具有T下限。

void forEach(Consumer<? super T> consumer);
Run Code Online (Sandbox Code Playgroud)

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

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

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