Over a million developers have joined DZone.
Platinum Partner

Groovy Goodness: Apply Mixin to Object Instances

· Java Zone

The Java Zone is brought to you in partnership with AppDynamics. Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems.

In Groovy we can add extra functionality to a class with so-called mixins. In the previous blog post we added extra functionality to a class, but we can also apply run-time mixins to an object instance. The syntax is slightly different, because we must use the mixin() method on the metaClass property of the object.

class Parrot {
    static String speak(Message text) {
        /"$text" Polly wants a cracker!/
    }
}

// Runtime mixin on String object instead of class. 
String s = 'Groovy is Gr8'
s.metaClass.mixin Parrot

assert s.speak() == '"Groovy is Gr8" Polly wants a cracker!'


String other = 'Groovy and Grails'
try {
    other.speak()
} catch (MissingMethodException e) {
    assert e.message.startsWith('No signature of method: java.lang.String.speak() is applicable for argument types: () values: []')
}

 

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}