【问题标题】:How to refer to the outer class in another instance of a non-static inner class?如何在非静态内部类的另一个实例中引用外部类?
【发布时间】:2010-09-23 12:14:27
【问题描述】:

我正在使用 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
    }
}

除了声明getMyFoo() 方法之外,是否有语法可以引用otherFoo 参考? other.Foo.this 之类的东西(不起作用)?

【问题讨论】:

    标签: java syntax reference inner-classes


    【解决方案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);
        }
    }
    

    【讨论】:

    • 这不能回答问题。事实上,这几乎是他试图避免的。
    【解决方案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(); 的创建限制为一个实例,我会说这更干净。

    【讨论】:

    • 假设 Bar 的构造函数是私有的,实例是由 Foo 上定义的工厂方法创建的;此外,Bar 的每个实例都应该绑定到 Foo 的一个实例。使用静态内部类可以做到这一点,但语言特性的重点是简化这种用法。
    • 哦,两个类都需要能够引用彼此的私有成员。
    • 在我的特殊情况下, Bar 是抽象的,工厂方法返回匿名类的对象,扩展 Bar 实现了在 Bar 中定义为抽象的公共方法;实现关闭了传递给各个工厂方法的参数范围。
    • 当然,覆盖等于而不覆盖哈希码会破坏 Object 的契约;酒吧需要有 public int hashcode() { return foo.hashcode(); }
    【解决方案3】:

    没有。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      相关资源
      最近更新 更多