Mostrando entradas con la etiqueta MOP. Mostrar todas las entradas
Mostrando entradas con la etiqueta MOP. Mostrar todas las entradas

sábado, julio 11, 2009

Groovy Metaclass

One of my favourites Groovy´s features is its MOP architecture. It allow us introducing new methods at runtime thanks to the metaClass.

We can define a new class

class SampleClass {
// class field
def propertyOne
// one sample Closure
def closureOne = {
println "I´m the closure one"
}
}

Now we add a new method at runtime

SampleClass.metaClass.runtimeAddedMethod = {
println "I´m runtimeAddedMethod"
}

Declare a new instance an test all the methods

def instance = new SampleClass()

Call to the closure declared in class definition

instance.closureOne()

Call to the method added at runtime

instance.runtimeAddedMethod()

We add a method to the "instance" too

instance.metaClass.instanceRuntimeAddedMethod = {
println "I´m the method added at runtime to a single instance"
}

instance.instanceRuntimeAddedMethod()

Bye!!