Jake Jake - 3 months ago 22
Groovy Question

Can Groovy dynamically add or override a method on a POJO?

If I have

// java
class MyClass {
public String getName() {
return "hector";
}
}


and an instance of this class. Can Groovy override the getName() method on the instance?

Answer

Of course you can using Dynamic MetaClass.

Your case is specifically covered by the following example :

def object = new MyClass();
object.metaClass.getName = { "Jake" }
assert "Jake" == object.getName()
Comments