如何理解使用“return this”时返回的方法

How to understand what method is returning when "return this" is used

提问人:blekione 提问时间:1/1/2015 最后编辑:blekione 更新时间:1/1/2015 访问量:144

问:

我正在阅读“Thinking in Java”,在解释关键字的段落中,作者使用下面的示例this

public class Leaf {
    int i = 0;
    Leaf increment() {
        i++;
        return this;
    }
    void print() {
        System.out.println("i = " + i);
    }
    public static void main(String[] args) {
        Leaf x = new Leaf();
        x.increment().increment().increment().print();
    }
}

我想知道的是,如何理解该方法返回的内容?作者解释说,它返回对当前对象的引用。这是否意味着该语句正在返回一种(我知道引用是什么意思)?而开始语句后先执行,变成?increment()x.increment()xx.increment().increment().increment().print();x.increment()x.increment().increment().print();

这对我来说听起来合乎逻辑,但我不确定我是否理解正确。

Java 流利

评论

2赞 Vince 1/1/2015
它正在返回当前实例。当您构造一个对象并从中调用该方法时,它将返回您从中调用该方法的对象,从而允许您在它的基础上调用更多方法
0赞 markspace 1/1/2015
请记住,“当前对象”可以是 的子类。所以在这种情况下,它返回一个 ,但一般来说,它返回一个或一个子类(注意这不是一个类)。LeafLeafLeafLeafLeaffinal
0赞 Sirko 1/1/2015
en.wikipedia.org/wiki/Method_chaining

答:

1赞 dkatzel 1/1/2015 #1

的方法签名是increment()

Leaf increment() 

它说它返回一个实例。Leaf

返回正在调用的 Leaf 类的实例(在本例中称为 )。return thisx

x.increment().increment().increment().print();

x.increment();
x.increment();
x.increment();
x.print();
3赞 Mureinik 1/1/2015 #2

return this返回当前实例,如果您想继续对其应用更改,这将非常方便。

JDK 的一个很好的例子是 StringBuilder。例如,这段代码没有错:

StringBuilder builder = new StringBuilder();
builder.append("welcome");
builder.append("to");
builder.append("StackOverflow");

但这看起来不是好多了吗?

StringBuilder builder = new StringBuilder().append("welcome").append("to").append("StackOverflow");

评论

0赞 Rikki Gibson 1/1/2015
在我看来,它最好作为带有换行符的单个语句。
1赞 Daniel 1/1/2015
可以在此处找到有关方法链接的不错资源。
0赞 blekione 1/1/2015
@Daniel - 谢谢你的链接。我读过它,它听起来对我来说是正确的,因为我理解它是对的,但我还不知道,从技术上讲,它是如何命名的
0赞 Daniel 1/1/2015
@FlenMK - 有关正确的命名,请在 programmers.SE 检查注意:我以前见过这被称为链式构建器模式)。
0赞 blekione 1/1/2015
那么让所有 setter 或类方法返回其类数据类型而不是 void 是不是个好主意?
1赞 Andres 1/1/2015 #3

您可以可视化为隐藏参数,其中包含对执行方法的实例的引用。要知道每个执行包含的内容,您必须查看将方法与实例分开的点左侧的内容。thisthis