我注意到使用Java 8方法引用的未处理异常有些奇怪.这是我的代码,使用lambda表达式() -> s.toLowerCase():
public class Test {
public static void main(String[] args) {
testNPE(null);
}
private static void testNPE(String s) {
Thread t = new Thread(() -> s.toLowerCase());
// Thread t = new Thread(s::toLowerCase);
t.setUncaughtExceptionHandler((t1, e) -> System.out.println("Exception!"));
t.start();
}
}
Run Code Online (Sandbox Code Playgroud)
它打印"Exception",所以它工作正常.但是当我Thread t改为使用方法引用时(甚至IntelliJ建议):
Thread t = new Thread(s::toLowerCase);
Run Code Online (Sandbox Code Playgroud)
异常没有被捕获:
Exception in thread "main" java.lang.NullPointerException
at Test.testNPE(Test.java:9)
at Test.main(Test.java:4)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Run Code Online (Sandbox Code Playgroud)
有人能解释一下这里发生了什么吗?
我遇到过使用方法引用但没有使用lambdas的问题.该代码如下:
(Comparator<ObjectNode> & Serializable) SOME_COMPARATOR::compare
Run Code Online (Sandbox Code Playgroud)
或者,与lambda,
(Comparator<ObjectNode> & Serializable) (a, b) -> SOME_COMPARATOR.compare(a, b)
Run Code Online (Sandbox Code Playgroud)
从语义上讲,它是完全相同的,但实际上它是不同的,因为在第一种情况下,我在其中一个Java序列化类中得到一个异常.我的问题不是关于这个例外,因为实际的代码是在一个更复杂的上下文中运行的,这个上下文已经被证明在序列化方面有奇怪的行为,所以如果我提供更多的细节,它会让它太难以回答.
我想要了解的是这两种创建lambda表达式的方法之间的区别.