Mixins for Java

Just for fun, I decided to implement mixins for Java, then record a screencast demonstrating how it works whilst at the same time trying to say “Um” as little as possible (I succeeded on the first two counts and failed on the last).


Click here to skip to the screencast

A Mixin is a bit of re-usable code that can be mixed in to classes. It is a form of code re-use more flexible than inheritance and less dangerous than multiple-inheritance. It works like this:

// this is a mixin: an interface labeled with a default implementation
@MixinType(implementation = HelloMessageBearer.class)
interface MessageBearer {
    public String getMessage();
// this is a mixin implementation. Classes implementing MyMixin will
// automatically have this implementation code mixed into them
class HelloMessageBearer implements MessageBearer {
    public String getMessage() { return "Hello World!"; }
// this is a class that uses the MessageBearer mixin
abstract class MessagePrinter implements MessageBearer {
    public void printMessage() {
        // code can refer to methods of the mixin interface
        System.out.println("message: " + this.getMessage());
// Demo code. Because this is a runtime library,
// "MixinSupport.create(X.class)" must be used instead of "new X()"
MessagePrinter printer = MixinSupport.create(MessagePrinter.class);
printer.printMessage(); // outputs "message: Hello World!"

Mixins for Java is a pure-Java runtime library that implements mixins in a type-safe way without requiring either a preprocessor (as JAMIE does) or whole new compiler (as AspectJ does).

All code is BSD licensed and available at The Mixins for Java Github repo.


The screencast requires flash and sound. You should click the “full screen” icon in the bottom right for best quality. If you don’t have the flash player, you can download the mp4 file here.

Leave a Reply

Your email address will not be published. Required fields are marked *