在Java中调用方法后会发生什么

在Java中调用方法后会发生什么

本文介绍了在Java中调用方法后会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来像一个愚蠢的问题,但我发现很难做到这一点。我问过不同的人,但无法得到理想的答案。

This looks like a silly question but I found it is hard to get it right. I have asked different people but couldn't get an ideal answer.

我想知道在Java中调用普通方法后会发生什么(在单线程环境中提供) )。

I want to know what happens after we call a normal method in Java (Provided in a single threaded environment).

我的理解是:


  1. 所有当前堆栈变量都是poped -up和存储在哪里(哪里?)

  2. 当前方法调用暂停

  3. 新调用方法的参数被推送到堆栈

  4. 方法代码运行

  5. 方法运行完毕后,堆栈再次清空,旧堆栈内容再次恢复。 (如果函数返回值会怎么样?)。

  6. 代码继续调用方法。

  1. All current stack variables are poped-up and stored somewhere (where?)
  2. The current method call halts
  3. The arguments of the newly called method are pushed to the stack
  4. The method code runs
  5. After the method finished running, the stack is again emptied and the old stack contents is again restored. (What happened if the function returns a value?).
  6. Code continues with the calling method.

这是一个非常不完整且可能错误的答案。有人可以提供更详细的描述吗?

This is a very incomplete and possibly wrong answer. Can someone provide a more detailed description?

非常感谢。

推荐答案

不,这实际上相当准确:

No, that's actually fairly accurate:

1)当前堆栈变量保留在堆栈上

1) current stack variables remain on the stack

2)当前方法暂停

3)新调用方法的参数被推送到堆栈

3) The arguments of the newly called method are pushed to the stack

4)方法代码运行

5)方法运行完毕后,我们弹出堆栈。被调用方法的堆栈变量不再有效 - 此时它们不再存在。

5) After the method finished running, we pop the stack. The called method's stack variables are no longer valid - they no longer "exist" at this point.

6)我们将返回值(如果有)传递给调用者

6) We pass the return value (if any) to the caller

7)代码继续调用方法。所有它的堆栈变量都保持不变。

7) Code continues with the calling method. All it's stack variables remain intact.

============================ ==

==============================

ADDENDUM:

@Kevin -

@Kevin -


  • 从概念上讲,我认为你说得对。我澄清了几点,我希望有所帮助。

  • Conceptually, I think you got it just about right. I clarified a few points, I hope that helps.

如果你想深入了解JVM如何实现方法调用,David Wallace的链接非常好。

David Wallace's link is very good if you want to go in depth on how the JVM implements "method calling".

以下是堆栈工作原理的概述。任何堆栈,调用任何子程序 - 不仅仅是Java:

Here is a good overview on how "a stack" works. Any stack, calling any subroutine - not just Java: http://en.wikipedia.org/wiki/Call_stack

最后,Marko Topolnik是正确的。 现实几乎总是很复杂,它不适合简单,一刀切的答案。但我绝对认为你的理解是好的。至少在10,000英尺的水平。

Finally, Marko Topolnik is correct. "The reality" is almost always complex enough that it doesn't lend itself to a simple, one-size-fits all answer. But I definitely think your understanding is good. At least at the 10,000 foot level.

恕我直言......

IMHO...

这篇关于在Java中调用方法后会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:21