如何在非静态内部类的另一个实例中引用外部类?

时间:2008-11-21 18:42:27

标签: java syntax reference inner-classes

我正在使用Apache Commons EqualsBuilder为非静态Java内部类构建equals方法。例如:

import org.apache.commons.lang.builder.EqualsBuilder;

public class Foo {
    public class Bar {
        private Bar() {}

        public Foo getMyFoo() {
            return Foo.this
        }

        private int myInt = 0;

        public boolean equals(Object o) {
            if (o == null || o.getClass() != getClass) return false;

            Bar other = (Bar) o;
            return new EqualsBuilder()
                .append(getMyFoo(), other.getMyFoo())
                .append(myInt, other.myInt)
                .isEquals();
        }
    }

    public Bar createBar(...) {
        //sensible implementation
    }

    public Bar createOtherBar(...) {
        //another implementation
    }

    public boolean equals(Object o) {
        //sensible equals implementation
    }
}

除了声明other方法之外,是否有语法可以引用Foo的{​​{1}}引用?像getMyFoo()这样的东西(不起作用)?

3 个答案:

答案 0 :(得分:6)

没有。

最好的方法可能就是你的建议:在你的内部类中添加一个getFoo()方法。

答案 1 :(得分:2)

不,没有吸气剂就不可能。 'this'关键字将始终指向当前实例。我很好奇你为什么要这样做......看起来你正在以错误的方式做作曲。

public class Foo {

  public Bar createBar(){
    Bar bar = new Bar(this)
    return bar;
  }
}

public class Bar {
  Foo foo;
  public Bar(Foo foo){
    this.foo = foo;
  }

  public boolean equals(Object other) {
    return foo.equals(other.foo);
  }
}

因为使用Foo.this限制了内部类的创建(Foo myFoo = new Foo(); myFoo.new Bar();对于一个实例我会说这更清晰。

答案 2 :(得分:-1)

是:

public class Foo {
    public class Bar {
        public Foo getMyFoo() {
            return Foo.this;
        }
    }
    public Foo foo(Bar bar) {
        return bar.getMyFoo();
     }
    public static void main(String[] arguments) {
        Foo foo1=new Foo();
        Bar bar1=foo1.new Bar();
        Foo foo=(new Foo()).foo(bar1);
        System.out.println(foo==foo1);
    }
}