2008-11-21 42 views
13

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

是否有语法由我可以参考otherFoo参考除了声明getMyFoo()方法?像other.Foo.this(这不起作用)?

回答

5

最好的办法可能是你的建议:添加的getFoo()方法来你的内部类。

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限制创建内部类的(美孚myFoo =新的Foo(); myFoo.new栏();以一个实例我说这是更清洁

+0

假设酒吧的构造函数是私有和实例是通过在富定义的工厂方法创建的;还有,酒吧的每个实例应绑定到富的一个实例,这是可能的静态内部类要做到这一点,。但是语言特征的全部重点在于简化这种使用方法 – 2008-11-21 20:31:16

+0

呵呵,而且这两类他们需要能够引用彼此的私人成员。 – 2008-11-21 20:31:57

-1

YES:

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); 
    } 
} 
相关问题