Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 162 ]

The difficulty with method pointers to instance methods is being sure what instance
the method pointer is referencing. In essence, an instance method pointer violates
the encapsulation rules for the object by passing control to an object that is outside
the direct control of a class. So I recommend caution when using them. However,
method pointers when applied to static methods can be a very useful way to create
DSL shortcut keywords.


Metaprogramming and the Groovy MOP


In a nutshell, the term metaprogramming refers to writing code that can dynamically
change its behavior at runtime. A Meta-Object Protocol (MOP) refers to the
capabilities in a dynamic language that enable metaprogramming. In Groovy,
the MOP consists of four distinct capabilities within the language: reflection,
metaclasses, categories, and expandos.


The MOP is at the core of what makes Groovy so useful for defining DSLs. The MOP
is what allows us to bend the language in different ways in order to meet our needs,
by changing the behavior of classes on the fly. This section will guide you through
the capabilities of MOP and, based on what we learn, we will later dissect some
builder code in order to understand how builders work under the covers.


Reflection


To use Java reflection, we first need to access the Class object for any Java object in
which we are interested through its getClass() method. Using the returned Class
object, we can query everything from the list of methods or fields of the class, to the
modifiers that the class was declared with. In the following code, we see some of the
ways that we can access a Class object in Java and the methods we can use to inspect
the class at runtime:


import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Reflection {
public static void main(String[] args) {
String s = new String();
Class sClazz = s.getClass();
Package _package = sClazz.getPackage();
System.out.println("Package for String class: ");
System.out.println(" " + _package.getName());
Class oClazz = Object.class;
System.out.println("All methods of Object class:");
Method[] methods = oClazz.getMethods();
for(int i = 0;i < methods.length;i++)
System.out.println(" " + methods[i].getName());

http://www.ebook3000.com
Free download pdf