Java如何知道void方法何时完成其方法体?

ree*_*nes 7 java methods void

假设我有一些代码:

public int doSomething(int x)
{
    otherMethod(x);
    System.out.println("otherMethod is complete.");
    return 0;
}

public void otherMethod(int y)
{
    //method body
}
Run Code Online (Sandbox Code Playgroud)

由于otherMethod的返回类型为void,该doSomething方法如何知道何时otherMethod完成,因此它可以转到下一个类似并打印" otherMethod已完成".

编辑:添加return 0;到doSomething方法,所以示例代码将编译.

Lux*_*ode 14

解析器知道执行结束的位置,甚至添加一个返回,例如:

 public static void main(String args[])  {

}
Run Code Online (Sandbox Code Playgroud)

编译为:

 public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 34 L0
    RETURN <------ SEE?
   L1
    LOCALVARIABLE args [Ljava/lang/String; L0 L1 0
    MAXSTACK = 0
    MAXLOCALS = 1
}
Run Code Online (Sandbox Code Playgroud)

这同样适用于您的代码(尽管我已经在返回0中添加了代码,因为您的代码无法编译):

 public int doSomething(int x)
    {
        otherMethod(x);
        System.out.println("otherMethod is complete.");
        return 0;
    }

    public void otherMethod(int y)
    {
        //method body
    }
Run Code Online (Sandbox Code Playgroud)

编译代码:

public doSomething(I)I
   L0
    LINENUMBER 38 L0
    ALOAD 0
    ILOAD 1
    INVOKEVIRTUAL TestRunner.otherMethod (I)V
   L1
    LINENUMBER 39 L1
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "otherMethod is complete."
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L2
    LINENUMBER 40 L2
    ICONST_0
    IRETURN
   L3
    LOCALVARIABLE this LTestRunner; L0 L3 0
    LOCALVARIABLE x I L0 L3 1
    MAXSTACK = 2
    MAXLOCALS = 2

  // access flags 0x1
  public otherMethod(I)V
   L0
    LINENUMBER 46 L0
    RETURN <-- return inserted!
   L1
    LOCALVARIABLE this LTestRunner; L0 L1 0
    LOCALVARIABLE y I L0 L1 1
    MAXSTACK = 0
    MAXLOCALS = 2
}
Run Code Online (Sandbox Code Playgroud)