Mixins with pure Java

Implementation of mixins using AOP (AspectJ) or source-code modification (JaMoPP)

In object-oriented programming languages, a mixin refers to a defined amount of functionality which can be added to a class. An important aspect of this is that it makes it possible to concentrate more on the properties of a particular behaviour than on the inheritance structures during development.

In Scala for example, a variant of mixins can be found under the name of “traits”. Although Java does not provide direct support for mixins, these can easily be added on with a few annotations, interfaces and some tool support.

Occasionally you read in a few online articles that mixins are incorporated into Java version 8. Unfortunately, this is not the case. A feature of the Lambda project (JSR-335) are the so-called “Virtual Extension Methods” (VEM).

Whilst these are similar to mixins, they do have a different background and are significantly more limited in functionality. The motivation for the introduction of VEMs is the problem of backward compatibility in the introduction of new methods in interfaces.

As “real” mixins are not expected in the Java language in the near future, this article intends to demonstrate how it is already possible to create mixin support in Java projects now, using simple methods. To do this, we will discuss two approaches: using AOP with AspectJ and using source-code modification with JaMoPP.

Why not just inheritance?

When asked at an event “What would you change about Java if you could reinvent it?James Gosling, the inventor of Java is said to have answered “I would get rid of the classes“.

After the laughter had died down, he explained what he meant by that: inheritance in Java, which is expressed with the “extends” relationship, should – wherever possible – be replaced by interfaces [Why extends is evil].

Any experienced developer knows what he meant here: inheritance should be used sparingly. It is very easy to misuse it as a technical construct to reuse code, and not to model a technically motivated parent-child relationship with it.

But even if one considers such a technically motivated code reuse as legitimate, one quickly reaches its limits, as Java does not allow multiple inheritance.

Mixins are always useful if several classes have similar properties or define a similar behaviour, but these cannot be reasonably modelled simply via slim relationship hierarchies.

In English, terms which end in “able” (e.g. “sortable”, “comparable” or “commentable”) are often an indicator for applications of mixins. Also, when starting to write “Utility” methods in order to avoid a code duplication in the implementation of interfaces, this can be an indication of a meaningful case of application.

Mixins with AOP

So-called Inter-type declarations are an extremely simple possibility for implementing mixins, offered by the AspectJ Eclipse project. With these, it is possible – among other things – to add new instance variables and methods to any target class.

This will be shown in the following, based on a small example in Listing 1. For this, we will use the following terms:

  • Basis-Interface Describes the desired behaviour. Classes which the mixin should not use can use this interface.
  • Mixin-Interface Intermediate interface used in the aspect and implemented by classes which the mixin is to use.
  • Mixin-Provider Aspect which provides the implementation for the mixin.
  • Mixin-User Class which uses (implements) one or more mixin interfaces.

// === Listing 1 ===

/** Base-Interface */
public interface Named {
    public String getName();

/** Mixin-Interface */
public interface NamedMixin extends Named {

/** Mixin-Provider */
public aspect NamedAspect {
    private String NamedMixin.name;
    public final void NamedMixin.setName(String name) {
        this.name = name;
    public final String NamedMixin.getName() {
        return name;

/** Mixin-User */
public class MyClass implements NamedMixin {
   // Could have more methods or use different mixins

Listing 1 shows a complete AOP-based mixin example. If AspectJ is set up correctly, the following source text should compile and run without errors:

MyClass myObj = new MyClass();

It is possible to work quite comfortably with AOP variants, but there are also a few disadvantages which will be explored here.

First of all, inter-type declarations cannot deal with generic types in the target class. This is not absolutely necessary in many cases, but can be very practical. For example, it is possible to define the “Named” interface just as well with a generic type instead of “String”. It would then define the behaviour for any name types. The class used could then determine how the type of name should look.

A further disadvantage is that the methods generated by AspectJ follow their own naming conventions. This makes it difficult to search the classes using reflection, as you would have to reckon with method names such as “ajc$interMethodDispatch …”

Last but not least, without the support of the development environment, you cannot see the source code in the target class and are dependent on the interface declaration alone. This could, however, be seen as an advantage, since the using classes contain less code.

Appearance: Java Model Parser and Printer (JaMoPP)

An alternative to the implementation of mixins with AspektJ is offered by Java Model Parser and Printer (JaMoPP). Simply put, JaMoPP can read Java source code, present it as an object graph in the memory and transform (i.e. write) it back into text.

With JaMoPP, it is therefore possible to programmatically process Java code and thus automate refactoring or implement your own code analyses, for example. Technologically, JaMoPP is based on the Eclipse Modeling Framework (EMF) and EMFText. JaMoPP is jointly developed by the Technical University of Dresden and DevBoost GmbH and is freely available on GitHub as an open-source project.

Mixins with JaMoPP

In the following, we would like to take up the example from the AOP mixins and expand this slightly. For this, we will first define a few annotations:

  • @MixinIntf Indicates a mixin interface.
  • @MixinProvider Indicates a class which provides the implementation for a mixin. The implemented mixin interface is specified as the only parameter.
  • @MixinGenerated Marks methods and instance variables which have been generated by the mixin. The only parameter is the class of the mixin
  • provider.

In the following, we will also be expanding the interfaces and classes from Listing 1 with a generic type for the name. Only the class using the mixin defines which concrete type the name should actually have.

// === LISTING 2 ===

/** Base-Interface (Extended with generic parameter) */
public interface Named<T> {
    public T getName();

/** Mixin-Interface */
public interface NamedMixin<T> extends Named<T> {

/** Mixin-Provider */
public final class NamedMixinProvider<T> implements Named<T> {

    private T name;

    public void setName(T name) {
        this.name = name;

    public T getName() {
        return name;

/** Special name type (Alternative to String) */
public final class MyName {
    private final String name;

    public MyName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("name == null");
        if (name.trim().length() == 0) {
            throw new IllegalArgumentException("name is empty");
        this.name = name;

    public String toString() {
        return name;


In the class which the mixin is to use, the mixin interface is now implemented again as shown in Listing 3. In order to “blend” the fields and methods defined by the mixin provider into the MyClass class, a code generator is used.

With the help of JaMoPP, this modifies the MyClass class and adds the instance variables and methods provided by the mixin provider.

// === LISTING 3 ===

/** Mixin-User */
public class MyClass implements NamedMixin<MyName> {
    // Could have more methods or use different mixins

In doing this, the code generator does the following. It reads the source code of every class, similarly to the normal Java compiler, and, in doing so, examines the amount of implemented interfaces.

If a mixin interface is present, i.e. an interface with the annotation @MixinIntf, the corresponding provider is found and the instance variables and methods are copied into the class which is implementing the mixin.

In order to initiate the generation of mixin codes, there are currently two options: using an Eclipse plug-in directly when saving or as a Maven plug-in as part of the build.

Installation instructions and the source code of both plug-ins can be found on GitHub in the small SrcMixins4J project. There is also an on-screen video available there, which demonstrates the use of the Eclipse plug-in. Listing 4 shows the how the modified target class then looks.

// === LISTING 4 ===

/** Mixin-User */
public class MyClass implements NamedMixin<MyName> {

    private MyName name;

    public void setName(MyName name) {
        this.name = name;

    public MyName getName() {
        return name;


If the mixin interface is removed from the “implements” section, all of the provider’s fields and methods annotated with “@MixinGenerated” will be deleted automatically. Generated code can be overridden at any time by removing the “@MixinGenerated” annotation.


Click on the following image to open a Flash video that demonstrates the Eclipse plugin:

Screenshot Eclipse


As native support of mixins in the Java language standard is not expected in the foreseeable future, it is currently possible to make do with just some AOP or source-code generation. Which of the two options you choose depends essentially on whether you prefer to keep the mixin code separate from your own application code or whether you want them directly in the respective classes.

In any case, the speed of development is significantly increased and you will concentrate less on inheritance hierarchies and more on the definition of functional behaviour.

Neither approach is perfect. In particular, conflicts are not automatically resolved. Methods with the same signature from different interfaces which are provided by different mixin providers will, for example, lead to an error in a class which uses both mixins.

Those seeking anything more would have to transfer to another language with native mixin support, such as Scala.


7 thoughts on “Mixins with pure Java

  1. Hi,
    this looks very interesting!

    Do the SrcMixins4J Eclipse plug-ins also work with Eclipse Kepler (Version 4.3.0)?

    I’ve got the following error when i tried it out today:

    java.lang.IllegalStateException: Annotation is unresolved: org.emftext.language.java.classifiers.impl.ClassImpl@1ff3dbe (eProxyURI: platform:/resource/srcmixins4j-eclipse-example/src/org/fuin/srcmixins4j/test/PackageableMixinProvider.java#EMFTEXT_INTERNAL_URI_FRAGMENT_1_MixinProvider)
    at org.fuin.srcmixins4j.core.SrcMixins4JUtils.getAnnotationInstance(SrcMixins4JUtils.java:143)
    at org.fuin.srcmixins4j.core.SrcMixins4JAnalyzer.analyze(SrcMixins4JAnalyzer.java:93)
    at org.fuin.srcmixins4j.core.SrcMixins4JAnalyzer.analyze(SrcMixins4JAnalyzer.java:59)
    at org.fuin.srcmixins4j.plugin.SrcMixins4JCompilationParticipant.buildStarting(SrcMixins4JCompilationParticipant.java:97)
    at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.notifyParticipants(AbstractImageBuilder.java:567)
    at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:289)
    at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:60)
    at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:254)
    at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:173)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:726)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

    Any help would be greatly appreciated!

    Thanks and regards,

    1. Hi Ronny,

      I must admit, that I haven’t tried it out yet with Eclipse Kepler, but I’m going to check it.


  2. Hallo Michael,

    ich habe festgestellt, dass SrcMixins4J in der Version 0.2.1 durchaus in Eclipse Kepler funktioniert. Dies allerdings nur bis zum ersten Build-Fehler (‘Building Workspace’ has encountered a problem…), danach muss ich jeweils sogar Eclipse neu starten, um den diesen wieder wegzukriegen.

    Ein Problem scheint es aber nur schon zu geben, wenn im srcmixins4j-eclipse-example-Projekt in der Klasse NamedMixinProvider ein zusätzliches Feld z.B.

    private String field;

    definiert wird. In der Klasse MyClass (in welche dieses Mixin eingemischt wird) wird dann generiert:

    private field;

    Bei der Verwendung eines primitiven Datentyps für das zusätzliche Feld scheint genau das allerdings zu funktionieren.

    Investierst du/ investiert ihr noch Zeit in dieses Projekt, oder war SrcMixins4J mehr ein PoC von JaMoPP und wird nicht mehr aktiv weiterentwickelt?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s