有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 1 楼答案

    Java SE 7版本的JLS有以下示例,说明它是fooFunc()bazFunc()之前,但是我只能找到示例-我还没有找到指定它的关联语句:

    Example 15.12.4.1-2. Evaluation Order During Method Invocation

    As part of an instance method invocation (§15.12), there is an expression that denotes the object to be invoked. This expression appears to be fully evaluated before any part of any argument expression to the method invocation is evaluated. So, for example, in:

    class Test2 { 
    
        public static void main(String[] args) { 
            String s = "one"; 
            if (s.startsWith(s = "two")) 
                System.out.println("oops"); 
        } 
    }
    

    the occurrence of s before ".startsWith" is evaluated first, before the argument expression s = "two". Therefore, a reference to the string "one" is remembered as the target reference before the local variable s is changed to refer to the string "two". As a result, the startsWith method is invoked for target object "one" with argument "two", so the result of the invocation is false, as the string "one" does not start with "two". It follows that the test program does not print "oops".

  2. # 2 楼答案

    fooFunc()将首先执行,然后是bazFunc(),最后是barFunc()

    我们都同意fooFunc()必须在barFunc()有任何操作之前执行

    考虑到bazFunc()只在barFunc()需要它的参数时才会被调用,因此在fooFunc()之后就会发生这种情况

  3. # 3 楼答案

    首先fooFunc,然后bazFunc,最后barFunc

    下面是一些代码来演示它:

    public class OrderJava {
      public static void main(String[] args) {
        fooFunc().barFunc(bazFunc());
      }
    
      public static Bar fooFunc() {
        System.out.println("I am fooFunc!");
        return new Bar();
      }
    
      public static class Bar {
        public void barFunc(Object o) {
          System.out.println("I am barFunc!");
        }
      }
    
      public static Object bazFunc() {
        System.out.println("I am bazFunc!");
    
        return null;
      }
    }
    

    此代码的输出为:

    I am fooFunc!
    I am bazFunc!
    I am barFunc!
    
  4. # 4 楼答案

    这方面的文档是15.12.4. Run-time Evaluation of Method Invocation

    上面说在运行时,方法调用需要五个步骤。首先,可以计算目标引用。第二,计算参数表达式。第三,检查要调用的方法的可访问性。第四,找到要执行的方法的实际代码。第五,创建新的激活帧,如果必要时,控制转移到方法代码。"

    在该示例中,fooFunc()作为计算目标引用的一部分被调用,而bazFunc()是参数表达式之一,因此必须首先调用fooFunc()