aboutsummaryrefslogtreecommitdiff
path: root/docs/mixins/adding-fields.md
blob: c3533e90c1f0b2b494ffad03608dc12c21b81e7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Adding new fields and methods

The next step up is injecting fields and methods into a class. This allows you to store additional state in objects, or can serve as an alternative to accessors for more complex operations that need to access private state of a class.

```java
@Mixin(EntityArmorStand.class)
public class InjectCustomField {
    Color colorOverride_mymodid;

    public void setColorOverride_mymodid(Color color) {
        colorOverride_mymodid = color;
    }

    public Color getColorOverride_mymodid() {
        return colorOverride_mymodid;
    }
}
```

This mixin is a `class`, like all mixin (except for accessors) are. You can make the class abstract if you want. 

First we add a new field (of course with modid postfix) into every armor stand.

Then we also add a getter and a setter method for that field.

Right now we run into a problem. We can't access mixin classes directly, so we cannot simply cast the `EntityArmorStand` into a `InjectCustomField`. Instead we create an interface (inside of our regular code, not inside of the mixin package) and implement that interface in our mixin class. You can also implement other interfaces this way, not just your own.

```java
// Inside our regular code. Not in the mixin package
public interface ColorFieldAccessor {
    void setColorOverride_mymodid(Color color);
    Color getColorOverride_mymodid();
}

// And the updated mixin
@Mixin(EntityArmorStand.class)
public class InjectCustomField implement ColorFieldAccessor {
    Color colorOverride_mymodid;

    @Override
    public void setColorOverride_mymodid(Color color) {
        colorOverride_mymodid = color;
    }

    @Override
    public Color getColorOverride_mymodid() {
        return colorOverride_mymodid;
    }
}
```