java - 受其他两个泛型类型约束的泛型类型限制
问题描述
我试图使方法的泛型返回类型受参数的两个泛型类型的约束,从某种意义上说,它应该是两者中最低的常见类型。例如:
class Scratch {
static <T, U, R /*additional restrictions*/> R getLowestCommon(T t, U u) {
return null;
}
public static void main(String[] args) {
Object o = getLowestCommon("", 1);
CharSequence s = getLowestCommon("", new StringBuilder());
Number n = getLowestCommon(1L, 2D);
Collection<Integer> c = getLowestCommon(new ArrayList<Integer>(), new HashSet<Integer>());
// this should give an error because ArrayList's and HashSet's lowest common supertype is Collection
List<Integer> l = getLowestCommon(new ArrayList<Integer>(), new HashSet<Integer>());
}
}
我知道对交集类型的这种限制,但是有什么方法可以在 Java 中进行这种编译时限制吗?
解决方案
那么从 R 中声明T
和U
扩展呢?
static <T extends R, U extends R, R > R getLowestCommon(T t, U u)
推荐阅读
- snowflake-cloud-data-platform - 雪花数据库:想要使用表中列的值作为另一个表的选择语句中的列名
- java - Java 线程同步给出了奇怪的输出
- google-apps-script - 在 URL 中使用“导出”查询字符串从 GSheet 创建 PDF
- html - 面临问题引导菜单分区
- mysql - 当我的 column_string 有字母时,如何使用 ORDER BY column_string like column_int?
- python - 如何在 Django 中的模板中渲染?
- latex - 超过 Tex 容量 [字符串数 = 2078043]
- php - 如何在没有输入事件的情况下向 viber 发送消息?
- python-3.x - TypeError:在 SVM 训练期间,只能将 size-1 数组转换为 Python 标量
- amazon-web-services - 错误:连接 ECONNREFUSED 3.15.138.43:8080 我需要 IAM AWS_ACCESS_KEY_ID 吗?