Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Groovy's MetaClass used for?

Tags:

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

like image 947
Ant's Avatar asked Mar 17 '11 14:03

Ant's


People also ask

What is the purpose of MetaClass?

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.

What is MetaClass in Java?

A MetaClass describes a real Class with the purpose of providing to an IDE class level information, and delaying the loading of that class to the last possible moment: when an instance of the class is required. A MetaClass binds the Class object from its class name using the appropriate class loader.

What is groovy metaprogramming?

Metaprogramming is a programming technique of writing a program to modify itself or another program using metadata. In Groovy, it's possible to perform metaprogramming at both runtime and compile-time.

Does Java have MetaClass?

In Java there's a single metaclass: the instances of the class Class are used to represent the types of classes and interfaces.


1 Answers

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

like image 116
Sean Patrick Floyd Avatar answered Dec 15 '22 01:12

Sean Patrick Floyd