开发者

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

开发者 https://www.devze.com 2023-01-30 03:00 出处:网络
If I have // java class MyClass { public String getName() { return \"hector\"; } } and an instance of this class.Can Groovy override the getNam开发者_运维知识库e() method on the instance?Of course

If I have

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

and an instance of this class. Can Groovy override the getNam开发者_运维知识库e() method on the instance?


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号