泛型限定问题
AI-摘要
Tianli GPT
AI初始化中...
介绍自己
生成本文简介
推荐相关文章
前往主页
前往tianli博客
1、前言
首先看这段代码:
import java.util.function.Function;
class Scratch {
static class RoleInfo {
}
public static void main(String[] args) {
// 想让这两个通过
test(Object::hashCode, RoleInfo::hashCode, new RoleInfo());
test(Object::toString, RoleInfo::toString, new RoleInfo());
// 想让这个报错
test(Object::hashCode, RoleInfo::toString, new RoleInfo());
}
public static <T, A, R>
void test(Function<T, R> a,
Function<A, R> b,
T ad) {
}
}
可以看到test方法的第0、1参数分别是Function<T, R>以及Function<A, R>

2、解决方式
最后使用了超类型限定解决了,我们可以看到Integer和String都实现了Comparable接口并限定了其类型:
- String
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {}
- Integer
public final class Integer extends Number implements Comparable<Integer> {}
那么我们这里就可以利用这个特性:
import java.util.function.Function;
class Scratch {
static class RoleInfo {
}
public static void main(String[] args) {
// 想让这两个通过
test(Object::hashCode, RoleInfo::hashCode, new RoleInfo());
test(Object::toString, RoleInfo::toString, new RoleInfo());
// 想让这个报错
test(Object::hashCode, RoleInfo::toString, new RoleInfo());
}
public static <T, A, R extends Comparable<R>>
void test(Function<T, R> a,
Function<A, R> b,
T ad) {
}
}
实现效果如下

本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 leaflei
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果