Pregunta

Sample code:

public class A {
    B b = new B();
    int a = 17;
}

public class B {
    int getA() {
        // how to get 'a' field from object containing 'this' object 
    }
}

My question is as in comment in sample code. In general: how to access fields and methods from object containing 'this' object. In my example class B will be instantiated only as a field in class A.

¿Fue útil?

Solución

If your starting point is code in B, then you can't do that. There's no way to reach out and find everywhere that B is used in all classes in the VM.

Moreover, though, if you find yourself wanting to do that, it indicates that you need to revisit your class structure. For instance, you might have B accept an A argument in the B constructor:

public B(A owner) {
    // ...do something with owner object
}

That introduces fairly tight coupling between A and B, though, which can be an issue. You might instead abstract away the aspects of A that B needs to know about into an interface, have A implement that interface, and have B accept an argument typed using that interface.

Or avoid needing to have B know anything about A, which would usually be best.

Otros consejos

You have to either store a reference to the A instance:

public class A {
    B b = new B(this);
    int a = 17;
}

class B {
    public B(A a) {
        this.a = a;
    }

    private final A a;

    int getA() {
        return a.a;
    }
}

... or if A.a is meant as a constant, declare it as such:

public class A {
    B b = new B(this);
    public static final int a = 17;
}

class B {    
    int getA() {
        return A.a; // but then you could use A.a at the call site anyway
    }
}

Whichever works best for you depends on the actual problem you are trying to solve. You should post your real code for further advice.

You need to pass a reference to the this of object A when creating an object of class B:

public class A {
    B b = new B(this);
    int a = 17;
}

public class B {
    A mA = null;
    public B(A pA) { mA = pA; }
    int getA() {
        int a2 = mA.a;    
    }
}

Another possibility would be to declare the class B inside the class A. For such a class, a reference to the value of "this" of the enclosing object will automatically passed as an hidden parameter when creating an object of the enclosed class:

public class A {
    B b = new B();
    int a = 17;

  public class B {
    int getA() {
       int a2 = A.this.a;
    }
  }
}

Notice that if you declare the class B as static, that this will transform the inner class B as an ordinary top level class and that the value of this for the outer class will no longer be done.

try this:

class A {
    B b = new B(this);
    int a = 17;
}

and

class B {
    A a;
    public B(A a) {
        this.a=a;
    }
    int getA() {
        return a.a;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top