gpt4 book ai didi

java - Java 方法引用中表达式的运行时评估

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:47:59 25 4
gpt4 key购买 nike

Run-Time Evaluation of Method References部分在 Java 语言规范中提到:

At run time, evaluation of a method reference expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. Evaluation of a method reference expression is distinct from invocation of the method itself.

First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference expression completes abruptly. If the subexpression completes abruptly, the method reference expression completes abruptly for the same reason.

ExpressionNamePrimary 定义在 method reference expression syntax 中:

MethodReference:
  ExpressionName :: [TypeArguments] Identifier
ReferenceType :: [TypeArguments] Identifier
Primary :: [TypeArguments] Identifier
super :: [TypeArguments] Identifier
TypeName . super :: [TypeArguments] Identifier
ClassType :: [TypeArguments] new
ArrayType :: new

我对突出显示的部分很感兴趣,并想使用以下代码测试上述行为:

public class Test {

public static void main(String[] args) {
System.out.println("Testing...");
final Person p = null;
foo(p::getName); // I was expecting an NPE here
}

private static void foo(Supplier<String> supplier) {
System.out.println(supplier);

// supplier.get(); // uncommenting this causes an NPE, but not when evaluating
// the method reference, but rather when the method is invoked.
}

static class Person {
String getName() {
return "x";
}
}
}

但是,foo(p::getName) 行不会抛出 NullPointerException。我是否误解了 JLS 的上述引述?如果是,有人可以解释以上引文的更多含义或举例说明它会出现在哪里吗?

最佳答案

天哪!那是一个 eclipse bug (ECJ) ,它因 javac/java 而失败(我在示例中尝试了 9,但同样的事情发生在 8):

 Testing...
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at org.eugene.so.DeleteMe.main(DeleteMe.java:11)

关于java - Java 方法引用中表达式的运行时评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com