有没有可能在Java中引用 null
引用的方法引用?这样做可能是永远正确的,但可能导致其很难后来发现错误:在空引用上创建方法引用不会引发异常
public class Test {
void m() {
}
public static void main(String[] args) {
Test test = null;
Runnable fn = test::m; // no exception
System.out.println(fn); // prints Test$$Lambda$1/[email protected]
fn.run(); // throws a null pointer exception
}
}
你与Eclipse测试?我使用JDK 1.8.0_51进行了测试,并在预期的情况下抛出了NPE。这可能会回答这个问题,然后http://stackoverflow.com/questions/37413106/thread-setuncaughtexceptionhandler-and-java-8-method-reference/。因为它应该在'Runnable fn = test :: m'上抛出一个NPE。 – Tunaki
我投票结束这个问题作为题外话题,因为它询问的是不存在的行为。 –
@Tunaki是的,我在Eclipse中测试过,当我取消注释最后一行时,它不会抛出异常 – Michael