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>

1-泛型限定.png

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) {

    }
}

实现效果如下

2-泛型限定.png