Friday, July 2, 2010

Groovy tip: adding methods dynamically at runtime


From Groovy's perspective every class (including Java classes) have a meta-class associated to them. This meta-class can be used to obtain information on the underlying class or to add methods and properties on the fly. In other words, this is AOP made easy.

So let's say we have a Java class:

public class SuperHero {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And I want to add a constructor that takes a name as a parameter. I also want to add a method:

SuperHero.metaClass.constructor = {String name -> new SuperHero(name:name)}
SuperHero.metaClass.fight = {"BAM!"}

println new SuperHero("Batman").name
println new SuperHero("Batman").fight()

The constructor is just a closure that sets the property for us.

No comments:

Post a Comment