使用嵌套赋值更新表达式中的引用 [英] updating references in an expression with a nested assignment

查看:139
本文介绍了使用嵌套赋值更新表达式中的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看此示例代码,类似于此问题

Looking at this example code similar to this question:

public class A {
    public static void main(String args[]){
        A a = new A();
        System.out.println(a.equals((a = null)));
    }
}

这打印为false。为什么它不会因NullPointerException而失败?在equals方法可以运行之前必须处理赋值,但是在评估整行之前,不会以某种方式影响equals的引用?

This prints false. Why doesn't it fail with a NullPointerException? The assignment has to get processed before the equals method can run, but somehow that doesn't affect the reference that equals is called on until after the whole line is evaluated?

我没有看到它描述的Java语言规范在哪里,我在某处错过了吗?

I didn't see where in the Java language spec it describes this, did I miss it somewhere?

推荐答案

来自 JLS


在运行时,方法调用需要五个步骤。首先,可以计算目标参考。其次,评估参数表达式。第三,检查要调用的方法的可访问性。第四,找到要执行的方法的实际代码。第五,创建一个新的激活帧,必要时执行同步,并将控制转移到方法代码。

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

这表明在 a.equals((a = null))。发生以下步骤:

This shows that in a.equals((a = null)). the following steps occur:


  1. 计算的引用。这有时称为绑定方法调用。

  2. a = null 作为评估参数的一部分进行评估。它不会影响第1步。

  3. 检查等于(对象)的可访问性。

  4. JVM内部代码找到实际的字节码。

  5. 发生调用

  1. a's reference is computed. This is sometimes called "binding the method call".
  2. a=null is evaluated as part of evaluating arguments. It does not affect step 1.
  3. The accessibility of equals(Object) is checked.
  4. JVM internal code finds the actual bytecode.
  5. Invocation occurs

显然,参考 a 的确定 <$ em> 之前,以避免NPE。

Clearly, the reference of a is determined before a is nulled, averting an NPE.

这篇关于使用嵌套赋值更新表达式中的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆