【发布时间】:2020-05-10 11:41:14
【问题描述】:
我有以下代码
public class FunctionalInterfaceTest {
@FunctionalInterface
public interface FunctionThatThrows<T, R> {
R apply(T t) throws Exception;
}
public void perform() {
try {
unchecked((String x) -> Integer.parseInt(x)).apply("abc");
} catch (Exception e) {
System.out.println("Encountered exception" + e.getMessage());
}
}
public void perform1() {
try {
unchecked(<fill-in-here-using-method-reference>);
} catch (Exception e) {
System.out.println("Encountered Exception" + e.getMessage());
}
}
public <T, R> Function<T, R> unchecked(FunctionThatThrows<T, R> f) {
return (a) -> {
try {
return f.apply(a);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public static void main(String[] args) {
FunctionalInterfaceTest test = new FunctionalInterfaceTest();
test.perform();
test.perform1();
}
}
我想在 perform1 方法中使用方法引用来获得与 perform 方法中相似的结果。我尝试在 perform1 中使用像 Integer::parseInt 这样的方法引用,但它不起作用。如何对方法引用执行相同操作?为什么方法引用会出错?
【问题讨论】:
-
你试过
unchecked((FunctionThatThrows<String, Integer>) Integer::parseInt).apply("abc")吗?哪一种方式不起作用? -
@Naman 这行得通。为什么需要显式类型转换?
-
有多少个
parseInt可能与您的Integer::parseInt匹配?当你转换时,你明确告诉编译器 whichparseInt使用 -
我认为我们使用 java.lang.Integer 中的 parseInt 非常明确。为什么会模棱两可?
-
我不知道为什么编译器没有选择正确的方法,但这是一个与实际相关的问题吗?我的意思是,在现实生活中你会使用结果,比如
Function<String,Integer> f = unchecked(Integer::parseInt);...
标签: generics lambda java-8 method-reference functional-interface