User Tools

Site Tools


tutorial:mixin_tips

This is an old revision of the document!


Mixin Tips

Why make a class abstract?

1. Prevent instantiation

It's fair to say that you should never instantiate a mixin class, mainly because the class doesn't make sense to java if it isn't used in a mixin environment, and there are other ways to access methods declared in a mixin.

Declaring a mixin class abstract doesn't affect it's function, and it becomes protected against accidental instantiation.

MixinClass foo = new MixinClass(); // can't do that with an abstract class

2. Make more elegant shadow methods

If you want to access a unaccessible method or field from your target class into your mixin class, you need to use @Shadow to make that method/field visible.

You can perfectly do this in normal classes by using a dummy body:

@Shadow
private void hiddenMethod() {/*dummy body*/}

But it's much more elegant to use an abstract method (and hence an abstract class):

@Shadow
private abstract void hiddenMethod(); // no dummy body necessary

3. Access the “this” instance

In mixin, if you want to access the “this” instance, you have to do a cast:

((TargetClass)(Object)this).field/method();

But that only works if your mixin class extends/implements everything that your target class does, which can be a pain because if one of those classes has an abstract method, you'll be in for some trouble.

Luckily, this can all be avoided by using an abstract class, in which case you don't have to implement the abstract methods and all problems are avoided.

UNDER CONSTRUCTION

tutorial/mixin_tips.1659702485.txt.gz · Last modified: 2022/08/05 12:28 by clomclem