是一个自我引用的对象证据代码设计错误

use*_*041 2 java coding-style

在我看到的一些代码中,我遇到了一个自我引用.

TestObject selfReference = this;
Run Code Online (Sandbox Code Playgroud)

是否有一个好的案例,你需要在对象中进行自我引用?这是不良编码设计或风格的标志吗?

编辑:

这是一个例子,如果我使用this它会抛出一个错误,但是当使用selfReference时,它会编译.


public class IFrame extends InternalFrame
{
    public IFrame()
    {
         addComponentListener(new java.awt.event.ComponentAdapter()
        {
            public void componentResized(java.awt.event.ComponentEvent evt) 
            {
                Window.setCurrComponent(this); //compile error
            }
            public void componentMoved(ComponentEvent evt)
            {
                Window.setCurrComponent(selfReference); //compiles correctly
            }
        });
    }
}

public class InternalFrame extends JInternalFrame
{
    protected InternalFrame selfReference = this;
}

public class Window
{
    InternalFrame currFrame;

    public static void setCurrComponent(InternalFrame iFrame)
    {
        currFrame = iFrame
    }
}

Oli*_*rth 14

是的,在某些情况下,隐含的自我引用可能是完全自然的.例如,考虑一个当前只包含单个元素的循环链表.

但是,拥有一个被调用的成员变量selfReference根本没有任何意义.

  • @jzd:是的,但那可能是OP改名,比如`head`.;-) (2认同)

Kaj*_*Kaj 9

我会抓住这个.我猜这个代码的作者不知道你可以写一个Classname.this当你想从嵌套类访问"外部这个".

也就是说,他创建了一个这样的结构:

class Executor {
    public void execute(Example example) {

    }
}

public class Example {

    Example selfReference = this;

    class Nested {
        public void method() {
            //Oh, oh, can't do this: 
            //new Executor().execute(this);
            //It gives:
            //The method execute(Example) in the type Executor is not applicable for the arguments (Example.Nested)

            //How the hell do I invoke the executor method from here?
            //lets do something really odd.
            new Executor().execute(selfReference);

            //This is what he should have done
            new Executor().execute(Example.this);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)