What is Groovy's MetaClass used for?

13,912

Solution 1

You're probably thinking of Groovy's MetaClass:

A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface and the contract with the Groovy runtime system. In general the compiler and Groovy runtime engine interact with methods on this class whilst MetaClass clients interact with the method defined by the MetaObjectProtocol interface


The Groovy MetaClass lets you assign behavior and state to Classes at runtime without editing the original source code, it's a layer above the original Class.

It's the mechanism used by Groovy to extend the Java JDK objects.

Example:

Object.class.metaClass.explode{-> println "Boom! ${delegate} Exploded!"}
"SomeString".explode();
12345.explode();

Output:

Boom! SomeString Exploded!
Boom! 12345 Exploded!

For more advanced usage, read this: MetaClasses

Solution 2

from Wikipedia

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Each language has its own metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact.

and

Support in languages and tools

The following are some of the most prominent programming languages that support metaclasses. Common Lisp, via CLOS Groovy Objective-C Python Perl, via the metaclass pragma, as well as Moose Ruby Smalltalk Some less widespread languages that support metaclasses include OpenJava, OpenC++, OpenAda, CorbaScript, ObjVLisp, Object-Z, MODEL-K, XOTcl, and MELDC.

Share:
13,912

Related videos on Youtube

Ant's
Author by

Ant's

Updated on September 20, 2020

Comments

  • Ant's
    Ant's over 3 years

    What is the use of Meta-Class in Groovy and other OO programming languages?

  • Ant's
    Ant's about 13 years
    in this case how does ${delegate}, prints somestring and 12345?
  • tim_yates
    tim_yates about 13 years
    the delegate is the object that the metaClass has been called against. In the first case, it's a String, then the second case it's an Integer
  • Sean Patrick Floyd
    Sean Patrick Floyd about 13 years
    delegate is an alias for this, because this has a different meaning in the context. delegate is the object the method is called on.