Over a million developers have joined DZone.

Groovy Goodness: Apply Mixin to Object Instances

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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 {
} catch (MissingMethodException e) {
    assert e.message.startsWith('No signature of method: java.lang.String.speak() is applicable for argument types: () values: []')


Building Identity Management, including authentication and authorization? Try Stormpath! Our REST API and robust Java SDK support can eliminate your security risk and can be implemented in minutes. Sign up, and never build auth again!


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}