Question

Code:

public class A{
  B b = new B();

  public class B{
    public void fun(){ send(A); }
  }

I want to do something with all A object in B. I can create method in A class:

private A getThis(){return this;}

But is it other solution (some keyword)?

Était-ce utile?

La solution

Try this code inside your inner class.

A.this

It should give you a reference to the enclosing instance from the outer class.

Here is a small example.

public class A {
    private B b = new B();

    public class B {
        public void fun() {

        }
        public A getEnclosing(){
            return A.this;
        }
    }

    public static void main(String[] args){
        A a = new A();
        System.out.println(a == a.b.getEnclosing());
    }
}

Autres conseils

Try

B b = new B(this);

Then B contructor

public B(A a) {
    this.a = a;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top