Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 7

[ 171 ]

/**
* Sets the given property to the new value.
*/
void setProperty(String propertyName, Object newValue);

/**
* Returns the metaclass for a given class.
*/
MetaClass getMetaClass();

/**
* Allows the MetaClass to be replaced with a
* derived implementation.
*/
void setMetaClass(MetaClass metaClass);
}

Pure Java classes used in Groovy do not implement this interface, but they have a
MetaClass assigned anyway. This MetaClass is stored in the MetaClass registry.
The MetaClass of any class can be found by accessing its .metaClass property:


class Customer {
int id
String firstName
String surname
String street
String city
}

// Access Groovy meta class
def groovyMeta = Customer.metaClass

// Access Java meta class
def javaMeta = String.metaClass

Metaclasses are the secret ingredients that make the Groovy language dynamic.
MetaClass maintains all of the metadata about a Groovy class. This includes all of its
available methods, fields, and properties. Unlike the Java Class object, the Groovy
MetaClass allows fields and methods to be added on the fly. So while the Java class
can be considered as describing the compile time behavior of the class, MetaClass
describes its runtime behavior. We cannot change the Class behavior of an object
but we can change its MetaClass behavior by adding properties or methods on
the fly.

Free download pdf