有 Java 编程相关的问题?

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

是否在java中接受的方法调用中传递“this”

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

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)是否可以接受


共 (6) 个答案

  1. # 1 楼答案

    是的,但是你应该注意两件事

    1. Passing this when the object has not been constructed yet (i.e. in its constructor)
    2. Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.
  2. # 2 楼答案

    这完全正常,完全可以接受

  3. # 3 楼答案

    如果有不太复杂的替代方法来实现相同的行为,那么在方法调用中传递当前对象是不好的做法

    根据定义,只要将this从一个对象传递到另一个对象,就会创建双向关联

    引用Martin Fowler的重构:

    Change Bidirectional Association to Unidirectional (200)

    Bidirectional associations are useful, but they carry a price. The price is the added complexity of maintaining the two-way links and ensuring that objects are properly created and removed. Bidirectional associations are not natural for many programmers, so they often are a source of errors

    ...

    You should use bidirectional associations when you need to but not when you don’t. As soon as you see a bidirectional association is no longer pulling its weight, drop the unnecessary end.

    因此,从理论上讲,当我们发现需要通过this时,我们应该听到警钟声,并努力思考解决当前问题的其他方法。当然,有时,在最后的手段下,这样做是有意义的

    此外,在长期重构代码以实现整体改进的过程中,经常需要临时破坏设计,做一些“不好的做法”。(后退一步,前进两步)

    在实践中,我发现我的代码通过避免像瘟疫一样的双向链接大大改进了

  4. # 4 楼答案

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

    所以使用它

    因为没有例子很难让人相信它是可以接受的(对这样一个问题的否定答案总是比较容易论证),我刚刚打开了一个最常见的java.langString类,当然我也发现了这种用法的例子,例如

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

    在大型“已接受”项目中寻找(this,你一定会找到的

  5. # 5 楼答案

    这表示当前对象。您所做的在系统上是正确的,但是如果您在同一个类中调用该方法,我认为没有必要这样做

  6. # 6 楼答案

    这没什么错。不好的做法是在构造函数内部执行相同的操作,因为您将引用尚未完全初始化的对象

    这里有一个类似的帖子:Java leaking this in constructor 他们解释了为什么后者是一种不好的做法