Skip to content

Commit e6c584a

Browse files
authored
create 'mixinoverride' tag (#184)
1 parent 6ac5b23 commit e6c584a

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

tags/faq/mixinoverride.ytag

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
type: text
2+
3+
---
4+
5+
When writing mixins, you may be tempted to override methods from superclasses in mixins like so:
6+
```java
7+
@Mixin(PlayerEntity.class)
8+
class PlayerEntityMixin {
9+
@Override
10+
public EntityPose getPose() {
11+
return EntityPose.SWIMMING;
12+
}
13+
}
14+
```
15+
16+
For mod compatibility reasons, you should not do this. Instead, you should use one of the following methods:
17+
```java
18+
19+
// Mixin the parent, and use instanceof to check what `this` is
20+
@Mixin(Entity.class)
21+
class EntityMixin {
22+
@ModifyReturnValue(
23+
method = "getPose",
24+
at = @At("RETURN")
25+
)
26+
private EntityPose overrideForPlayer(EntityPose pose) {
27+
// the compiler doesn't belive `this` can ever be `PlayerEntity`, so a cast to `Object` is required
28+
return (Object) this instanceof PlayerEntity ? EntityPose.SWIMMING : pose;
29+
}
30+
```
31+
32+
```java
33+
34+
// use submixin to conditionally modify the parent
35+
@Mixin(Entity.class)
36+
class EntityMixin {
37+
// 1. define a dummy handler in a mixin to the superclass, that does nothing, but is protected
38+
@WrapMethod(
39+
method = "getPose"
40+
)
41+
protected EntityPose overrideForPlayer(Operation<EntityPose> original) {
42+
return original.call();
43+
}
44+
45+
@Mixin(PlayerEntity.class)
46+
private static class PlayerEntityMixin extends EntityMixin /* !important! */ {
47+
// 2. Override the handler in the child mixin, and make the actual changes
48+
@Override
49+
protected EntityPose overrideForPlayer(Operation<EntityPose> original) {
50+
return EntityPose.SWIMMING;
51+
}
52+
}
53+
}
54+
```
55+
56+
Both of the above patterns can work for any mixin injector, and even when you just need to make small changes to the superclass.
57+
58+
The `instanceof` pattern is more direct, and can be simpler to understand, while the submixin pattern can lead to a code structure more similar to just overriding the target method and keeps all code relevant to a given class in a mixin to that class. the general agreement is that it doesn't matter which you pick; either is better than `@Override`.

0 commit comments

Comments
 (0)