Using Java 6, how can I implement a mixin? It is very easy and possible in Ruby. How can I get similar in Java?
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)
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:
Cons:
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.
Take a peek at http://code.google.com/p/javadude/wiki/AnnotationsMixinExample
It's using a set of annotations I've created.
Note: I'm working on a major update to the annotations, which includes some API breakage. I plan to release a new version in the next few weeks.
Faking mixins in Java: http://jonaquino.blogspot.com/2005/07/java-mixin-pattern-or-faking-multiple.html