2

I have a class that has this structure:

public class MyClass {

    private double myDouble;
    private MyObject myObject;

    public myMethod() {

        AnotherObject anotherObject = new AnotherObject();        
        anotherObject.getInfo(new Callback<String>() {
            @Override
            public void success(MyObject myObject) {
                this.myObject = myObject; // this is what I would like to do
            }

            // and a method for the failure case
        });

    }
}

Essentially, I am looking for a way to save the value of myObject that I get from the success method inside the instance variable myObject (this.myObject). Currently, with the above code, I get a "Cannot resolve symbol 'myObject'" message.

Is this possible?

user1301428
  • 1,743
  • 3
  • 25
  • 57
  • 1
    Did you try that? What errors did you get? – Tunaki Mar 12 '16 at 17:18
  • @Tunaki uhm, yeah... I get "cannot resolve symbol 'myObject'". I'll update the question. – user1301428 Mar 12 '16 at 17:20
  • 3
    Two ways: either `MyClass.this.myObject"; or much easier: simply avoid that the success method parameter shadows that name in the first place. Change the parameter name to "incomingObject"; and then myObject = incomingObject works fine. – GhostCat Mar 12 '16 at 17:20
  • And side note. I assume this is just example code, but MyClass, myObject and so on are pretty pure names for classes and variables .. – GhostCat Mar 12 '16 at 17:21
  • @Jägermeister your assumption is correct :) – user1301428 Mar 12 '16 at 17:22

1 Answers1

4

You are close, since you are within an inner class you have to prefix this with a little extra information:

MyClass.this.myObject = myObject;

Otherwise this refers to the anonymous Callback class you are defining.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
  • You probably mean "since you are within an inner class" – JB Nizet Mar 12 '16 at 17:24
  • Anonymous class is probably more correct, edited my answer. – Kevin DiTraglia Mar 12 '16 at 17:25
  • Not really. If the class was a named inner class (i.e. not anonymous), the OP would have the same problem. – JB Nizet Mar 12 '16 at 17:26
  • Thanks for the answer. While now I can call the class variable, do you have any idea why I might get a `null` value outside the callback? If I output the value of `MyClass.this.myObject` inside `success`, after the assignment, I get the correct value, but if I do it within `myMethod`, I get `null` – user1301428 Mar 12 '16 at 17:53
  • Your callback likely hasn't called back yet, you could call a separate method call within `success` to ensure myObject has been set before you try to manipulate it further. – Kevin DiTraglia Mar 12 '16 at 17:57
  • I opened another question since it's a different issue altogether, if you want to have a look: http://stackoverflow.com/questions/35961591/object-becomes-null-outside-of-callback-function/35961668#35961668 – user1301428 Mar 12 '16 at 18:35