Implement Mixin In Java? [closed]

Using Java 6, how can I implement a mixin? It is very easy and possible in Ruby. How can I get similar in Java?


You could use CGLIB for that. The class Mixin is able to generate a dynamic class from several interfaces / object delegates:

static Mixin    create(java.lang.Class[] interfaces,
                        java.lang.Object[] delegates)
static Mixin    create(java.lang.Object[] delegates)
static Mixin    createBean(java.lang.Object[] beans) 

Default Methods

I know the question said Java 6, but in Java 8 we'll have a pretty decent alternative: default methods.

We'll be able to add 'default' implementations of interface methods, so we can add new methods without breaking every class that implements the interface.

As long as your mixin doesn't need state, you can write code in an interface. Then your class can implement as many of these interfaces as it wants and boom, you've got mixins.

Is this an abuse of the system? A little bit, but it doesn't get into any multiple inheritance issues because there's no state.

Of course, that's also the biggest disadvantage with this approach.


I'd say just use object composition. Every time you want to throw in new functionality, compose another object into the class as a member. If you want to make all of your mixed-in classes of the same type, you can use an array as a member object where each element is composed with all of the others, and you can dispatch to a particular element.