Java中描述实例和参数的方法的执行顺序?
在声明中:
fooFunc().barFunc(bazFunc());
barFunc()
显然无法执行,直到bazFunc()
和fooFunc()
都完成
但是fooFunc()
和bazFunc()
的执行顺序有保证吗
相关(但不同!)问题:Order of execution of parameters guarantees in Java?
你可以在下面搜索框中键入要查询的问题!
在声明中:
fooFunc().barFunc(bazFunc());
barFunc()
显然无法执行,直到bazFunc()
和fooFunc()
都完成
但是fooFunc()
和bazFunc()
的执行顺序有保证吗
相关(但不同!)问题:Order of execution of parameters guarantees in Java?
# 1 楼答案
Java SE 7版本的JLS有以下示例,说明它是
fooFunc()
在bazFunc()
之前,但是我只能找到示例-我还没有找到指定它的关联语句:# 2 楼答案
fooFunc()
将首先执行,然后是bazFunc()
,最后是barFunc()
我们都同意
fooFunc()
必须在barFunc()
有任何操作之前执行考虑到
bazFunc()
只在barFunc()
需要它的参数时才会被调用,因此在fooFunc()
之后就会发生这种情况# 3 楼答案
首先
fooFunc
,然后bazFunc
,最后barFunc
下面是一些代码来演示它:
此代码的输出为:
# 4 楼答案
这方面的文档是15.12.4. Run-time Evaluation of Method Invocation
上面说在运行时,方法调用需要五个步骤。首先,可以计算目标引用。第二,计算参数表达式。第三,检查要调用的方法的可访问性。第四,找到要执行的方法的实际代码。第五,创建新的激活帧,如果必要时,控制转移到方法代码。"
在该示例中,
fooFunc()
作为计算目标引用的一部分被调用,而bazFunc()
是参数表达式之一,因此必须首先调用fooFunc()