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:
class Talk {
  // other stuff here
Invoking 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:
For more information about mixins, see:
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.

516,722 Spambots Blocked by Simple Comments