Only my share

Java , Groovy and others

Archive for March 2009

The beauty of Meta Object Programming in Groovy

with 2 comments

Hello there, see you again. In this article I will show you how MOP programming will be easy when you implement it in Groovy. This simple way is achieved by strong expressiveness of Groovy language. 

As you know, MOP or Meta Object Programming is one of good programming techniques that can change the behavior  of one object at runtime. It is very different if you are as a Java Programmer where all of object is created by static type class and the behavior of the object of this class cannot be changed at run time.

In the following code I’ll show you how MOP enable us to change the behavior (add more method) to the Class / Object at runtime.

String.metaClass.hitungPanjang = {
         ->
              delegate.size()
}

String test = “Aldry Deka Pratama”
println “The number of character in string : ” + test.hitungPanjang()

In this code I define a new method called “hitungPanjang” that will count the size of the String. This method will be attached to existing String class. After you attached the method and make a new instance of this class, then you can call the method you already defined to the class  through its object

Written by adpjhype

March 2, 2009 at 12:38 pm