Mousa
Mousa

Reputation: 2300

Is there a way to modify enclosing class reference?

I have enclosing and nested classes like this:

public class Promotion {
    protected int id;
    protected List<Image> images;
    //...

    public class Image {
        private String id;
        private String aspect_ration;

        public Promotion getPromotion() {
            return Promotion.this;    //<-- Always null.
        }
    }
}

The objects of this class are being automatically created and initialized by Gson from json strings.

For some reason (instantiating by Gson), in the nested class instances, the Promotion.this is null. Setting it manually is impossible, because the statement Promotion.this = promotion; causes compile error: Variable expected.

So is there any way to do something like this: (either by normal Java way, or some Java Reflection trick)

public class Promotion {
    //...

    public class Image {

        public void setPromotion(Promotion promotion) {
            Promotion.this = promotion;   //<-- Is not possible.
        }
    }
}

Upvotes: 0

Views: 120

Answers (1)

Mousa
Mousa

Reputation: 2300

I found a way myself by using Reflection. The method in question can be implemented like this:

public void setPromotion(Promotion promotion) throws IllegalAccessException
{
    try {
        Field enclosingThisField = Image.class.getDeclaredField("this$0");
        enclosingThisField.setAccessible(true);
        enclosingThisField.set(this, promotion);
    }
    catch (NoSuchFieldException e) {}
}

Edit: This is working in my environment (Java(TM) SE Runtime Environment (build 1.8.0_92-b14)), but I'm not sure if it's guaranteed to work on every JVM.

Upvotes: 2

Related Questions