从可比的返回通用java.util.function.Function返回

时间:2019-03-07 14:10:05

标签: java generics method-reference

我有一个返回java.util.Function<A, T>的方法,其中T是泛型类型。我需要T成为Comparable<T>的实例。尝试在getFunction()中返回方法引用,但出现错误:

Error:(9, 16) java: incompatible types: bad return type in method reference
    java.lang.Integer cannot be converted to T

这是MCVE:

import java.util.function.Function;

class Main {
    public static void main(String[] args) {
        System.out.println(getFunction(true).apply(new A(5)));
    }

    static <T extends Comparable<T>> Function<A, T> getFunction(boolean b) {
        if (b) return A::getX;
        else return A::getRandomString;
    }
}

class A {
    private Integer x;

    A(int x) {
        this.x = x;
    }

    Integer getX() {
        return x;
    }

    String getRandomString() {
        return "Hello Stack Overflow";
    }
}

我尝试使用通配符返回类型Function<A, ?>,但是后来我无法调用compareTo()。 有什么方法可以从这种类型安全的方法中返回Comparable吗?

0 个答案:

没有答案
相关问题