Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

groovy

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?

like image 910
Jake Avatar asked Dec 13 '10 16:12

Jake


1 Answers

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()
like image 59
Riduidel Avatar answered Nov 20 '22 00:11

Riduidel