在java中的方法调用接受实践中传递'this' [英] Is passing 'this' in a method call accepted practice in java

查看:524
本文介绍了在java中的方法调用接受实践中传递'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方法调用中传递当前对象是好/坏/可接受的做法。如:

Is it good/bad/acceptable practice to pass the current object in a method call. As in:

public class Bar{
    public Bar(){}

    public void foo(Baz baz){
        //  modify some values of baz
    }
}

public class Baz{
    //constructor omitted

    public void method(){
        Bar bar = new Bar();
        bar.foo(this);
    }
}

具体来说,是行 bar.foo(this)可以接受吗?

Specifically, is the line bar.foo(this) acceptable?

推荐答案

没有理由不使用它,是当前实例,使用它是完全合法的。事实上,通常没有简洁的方法可以省略它。

There's no reason not to use it, this is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.

所以要使用它。

因为很难说服它没有示例是可以接受的(对这样一个问题的否定答案总是更容易论证),我刚刚打开了一个最常见的java.lang类, String 一个,并且当然我找到了这种用法的实例,例如

As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the String one, and of course I found instances of this use, for example

1084        // Argument is a String
1085        if (cs.equals(this))
1086            return true;

寻找(此 in big接受项目,你会发现它。

Look for (this in big "accepted" projects, you won't fail to find it.

这篇关于在java中的方法调用接受实践中传递'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆