【问题标题】:I wonder what is happening in this Java code block我想知道这个 Java 代码块中发生了什么
【发布时间】:2012-01-23 05:28:42
【问题描述】:
Objectname.methodone()
.methodtwo()
.methodthree()
.methodfour();

以上这些说法是否与

Objectname.methodone();
Objectname.methodtwo();
Objectname.methodthree();
Objectname.methodfour();

谢谢,

【问题讨论】:

标签: java


【解决方案1】:

这取决于methodonemethodtwomethodthreemethodfour 的返回类型。发生了什么是你在Objectname 上调用methodone,在methodone 的返回类型上调用methodtwo 等等。

如果methodonemethodfour 都返回this,那么是的,这将是相同的。

这被称为method chaining

【讨论】:

    【解决方案2】:

    可能,如果每个方法的实现都以return this; 结尾,那么调用就可以像这样被链接起来。但有可能每个都返回一个对不同对象的引用,然后在该对象上调用“next”方法。

    【讨论】:

      【解决方案3】:

      不,它不像它那样

          Objectname.methodone().methodtwo().methodthree().methodfour();
      

      类似

       result = method1().method2(). ........ method n()
      

      它被称为方法链

      参考Method chaining in Java

      示例

      class Person
      {
              private final String name;
              private int age;
      
              public Person setName(final String name) {
                      this.name = name;
      
                      return this;
              }
      
              public Person setAge(final int AGE) {
                      this.age = AGE;
      
                      return this;
              }
      
              public void introduce() {
                      System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
              }
      
              // Usage:
              public static void main(String[] args) {
                      Person person = new Person();
                      // Output of this sequence will be: Hello, my name is Peter and I am 21 years old.
                      person.setName("Peter").setAge(21).introduce();
              }
      }
      

      来源:-http://en.wikipedia.org/wiki/Method_chaining

      【讨论】:

        【解决方案4】:

        不一定,在methodone的返回值上调用methodtwo,在methodtwo的返回值上调用methodthree等等。它们不会(不一定)在同一个对象上调用。

        等价于:

        MethodOneReturnType x = object.methodone();
        MethodTwoReturnType y = x.methodtwo();
        MethodThreeReturnType z = y.methodthree();
        

        【讨论】:

          【解决方案5】:

          这取决于这些方法返回什么。在methodone返回时调用methodtwo。如果methodone返回Objectname,那么它们是相同的。

          【讨论】:

            【解决方案6】:

            它们不太可能相同。想想比萨制造商。

            new PizzaBuilder().withDough("dough").withSauce("sauce").withTopping("topping").build();
            

            这构建了完整的比萨饼。而如果你单独调用 with 方法,它只会构建部分披萨。

            【讨论】:

              猜你喜欢
              • 2019-11-27
              • 1970-01-01
              • 1970-01-01
              • 2013-03-15
              • 2023-02-24
              • 2018-07-28
              • 1970-01-01
              • 2022-09-27
              • 1970-01-01
              相关资源
              最近更新 更多