Skip to content

Accessors

Reflxction edited this page Jul 16, 2021 · 3 revisions

Accessors are a feature of mixins that allow you to access normally inaccessible methods or fields. Implementing a mixin accessor is very simple.

Let's say we have this Point class

public class Point {  
  
  private final int x, y; // <-- fields are private and final
  
  public Point(int x, int y) {  
    this.x = x;  
    this.y = y;  
  } 
  
  private void secretMethod() { // <-- method is private
    System.out.println("Don't call me!");  
  }  
}

As we can see, x and y are both private and inaccessible. secretMethod() is also inaccessible. Now, let's implement accessors for these

import io.tunabytes.Accessor;
import io.tunabytes.Mixin;

@Mixin(Point.class)
public interface PointAccessor {
    
    @Accessor int getX();

    @Accessor void setX(int x); // we can even bypass final
    
    @Accessor int getY();
    
    @Accessor void callSecretMethod(); // we can also define the method name in @Accessor("secretMethod")
    
}

Great! All we need now to use our PointAccessor is to cast any Point to it.

Now let's test our new accessors

import io.tunabytes.bytecode.MixinsBootstrap;

public final class PointTest {

    public static void main(String[] args) {
        MixinsBootstrap.init();
        Point point = new Point(55, 94);
        ((PointAccessor) point).callSecretMethod();
        System.out.println(((PointAccessor) point).getX());
        System.out.println(((PointAccessor) point).getY());
    }
}

Output:

Don't call me!
55
94
Clone this wiki locally