java - 带有泛型参数接口的回调
问题描述
我有一个通用容器接口,用于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>
传递给我的班级?
解决方案
在MyContainer
中,Consumer
的类型参数可以具有T
下限。
void forEach(Consumer<? super T> consumer);
这样,消耗超类型的东西T
可以作为参数传入。
对于Consumer
自身,如果它可以处理 的超类型T
,那么它也可以处理 a T
。这是 PECS 的一部分 - 生产者扩展,消费者超级。
然后,在 中method
,您可以将 a 传递Consumer<Interface>
给forEach
。这里,T
是Implementation
。该类型Interface
是 的超类型Implementation
,因此下限允许这样做。
推荐阅读
- reactjs - React Form 与输入字段的持续时间以小时或分钟格式化为字符串
- python - 制作存在/不存在图表
- php - 如何使用 PHP 显示 SQL Server 表数据?
- mysql - 使用 Hive CASE 或 IF/ELSE 语句在 WHEN 子句中执行另一个操作
- vuejs2 - 带有键盘导航的 Vue 2 移动窗口
- arrays - 如何在二维数组中从中心扩展数字的半径
- typescript - 迭代对象时键入 key
- vega-lite - 列编码分面图的 Vega-lite 响应大小
- google-cloud-platform - 尽管有大量积压和可用实例,Google Cloud Run 仍无法扩展
- azure-devops - Azure DevOps Pipeline Step 打印变量值