Implement Mixin In Java?

Viewed 33549

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

17 Answers

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) 

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.

Since Java only supports single inheritance, that is not possible. Have a look at WP: Mixin.

EDIT: Because of the comments about interfaces: The cool thing about mixins is that you can combine them without writing the combination's code. With interfaces you have to implement the combination's functionality yourself (except one class you can extend)!

The simplest approach is to use static imports. It allows for code reuse that 'looks' like it's part of the class, but is really defined elsewhere.

Pros:

  • really easy
  • you can 'mixin' as many static imports as you like

Cons:

  • the static methods won't have access to 'this', so you'd have to pass it in manually
  • no state: your static methods can't have their own instance fields. They can only define their own static fields, which are then shared by any object calling the static method.
  • can't define public methods on the client class (the one with code being mixed into it). In Ruby, importing a mixin will actually define those public methods as public methods on your class. In Java, inheritance would be a better solution in this case (assuming you don't need to extend multiple classes)

Example:

import static my.package.MyHelperUtility.methodDefinedInAnotherClass;

public class MyNormalCode {
    public void example() {
        methodDefinedInAnotherClass();
    }
}

In the sense that a Ruby mix-in is the equivalent of a Java abstract class, no, you cannot implement a mix-in in Java. You can come close by using interfaces and thus defining absolutely no code in your mix-in, but you cannot directly achieve the same behavior as in a Ruby mix-in.

Related