1

I'm targeting a non-static nested class, e.g.

package whatever;
class Outer {
    public int x;
    class Inner {
        public void foo();
    }
}

And I would like to write a SpongePowered Mixin for the inner class that refers to a field of the outer class, e.g.

@Mixin(targets = "whatever.Outer$Inner")
class InnerMixin {
    @Overwrite
    public void foo() {
        System.out.println(Outer.this.x); //This doesn't work
    }
}

How can I do this?

Sören
  • 1,803
  • 2
  • 16
  • 23
The Zach Man
  • 738
  • 5
  • 15
  • Does this work for normal, non-inner classes? Does this @Mixin already exist, or is it something you'd like to exist? – Sören Jul 20 '23 at 18:39
  • Are you talking about [SpongePowered Mixin](https://github.com/SpongePowered/Mixin)s? If yes, please edit that into the question. – Sören Jul 20 '23 at 18:45
  • Yes, I am, edited. I couldn't find a tag for SpongePowered specifically, let me know if I missed one. – The Zach Man Jul 20 '23 at 19:06

1 Answers1

1

The inner class has a synthetic (final) field, often but not always called this$0, which contains the instance of the outer class. This field can be obtained by reflection as in this answer, or with a mixin it can be shadowed:

@Mixin(targets = "whatever.Outer$Inner")
class InnerMixin {
    @Shadow @Final Outer this$0;

    @Overwrite
    public void foo() {
        System.out.println(this$0.x);
    }
}
The Zach Man
  • 738
  • 5
  • 15