Cool Groovy features 4 – Mixins

A mixin is a way of inheriting methods from a class without the problems associated with multiple inheritance. Groovy supports both compile time and runtime mixins.

Compile time mixins

Supported with the @Mixin annotation. First define the class that will hold the method definitions:
class Dog {
  def talk() {
    "Woof, woof"
  }
}
Then mix in the method(s) to the target class:
@Mixin(Dog)
class Talk {
  // other stuff here
}
Invoking talk.talk() will now give “Woof, woof” as the response.

Runtime mixins

You can also add methods to classes you don’t own by using the mixin() static method call:
someoneElsesClass.mixin(Dog)
For more information about mixins, see: http://groovy.codehaus.org/Runtime+mixins
This entry was posted in Groovy and tagged . Bookmark the permalink.

Leave a Reply

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

HTML tags are not allowed.

506,508 Spambots Blocked by Simple Comments