我有一个返回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
吗?