This is part-1 in a series of tutorials about meta-programming in Groovy. Groovy provides excellent hooks for extending behavior of classes and objects at run-time. First, what is meta-programming? Meta-programming means writing programs that write programs. What this means is that programs are open for either modification or extention at any time during the process of compilation or runtime. Meta-programming allows you to write efficient programs that change behavior dynamically based on needs or input from the environment. Groovy accomplishes this using MOP(Meta Object Protocol). Groovy provides categories, meta-classes, exapandos, mixins, annotations etc. to accomplish this. First in this part I will discuss categories.

1) Categories - Categories allow methods to be added dynamically on any object. Let’s see the following example. In this example I have a StringUtil class that has method capitalize which capitalizes each word in a string.

def hello = "hello world HELLO WORLD"
class StringUtil {
  static String capitalize(String self) {
    return self.split(" ").collect { it[0].toUpperCase() + it[1..-1].toLowerCase()}.join(" ")
  }
}
use(StringUtil) {
  println hello.capitalize()
}
// prints "Hello World Hello World"

Lets see what is happening here Use is a method on class Object. Use accepts a class and closure as arguments. All the objects with in the closure will have access to the methods on the category class, in this case StringUtil. Groovy accomplishes this by providing a fresh list of properties and methods of the category class on the stack. These are the different ways Use can be used. This is taken from groovy jdk API.

  use(Class categoryClass, Closure closure)
    Scoped use method
  use(List categoryClassList, Closure closure)
    Scoped use method with list of categories
  use(Object[] array)
    Allows you to use a list of categories, specifying the list as varargs use(CategoryClass1, CategoryClass2) { This method saves having to wrap the the category classes in a list

Since groovy 1.6 is official now, groovy now provides compile time meta-programming using AST(Abstract Syntax Tree). Using this Categories can be created using @Category annotations. to be contd..

One Comment

  1. Subba Rao Pasupuleti says:

    nice article

Leave a Reply