Dynamically add a property or method to an object in groovy

一笑奈何 提交于 2019-12-03 04:15:14

If you just want to add the bye() method to the single instance g of the class Greet, you need to do:

g.metaClass.bye = { println "Goodbye, $name" }
g.bye()

Otherwise, to add bye() to all instance of Greet (from now on), call

Greet.metaClass.bye = { println "Goodbye, $name" }

But you'd need to do this before you create an instance of the Greet class

Here is a page on the per-instance metaClass

And here is the page on MetaClasses in general


Also, there's a bug in your constructor. You're missing who from infront of your [1..-1] and if the constructor is passed a String of less than 2 characters in length, it will throw an exception

A better version might be:

Greet( String who ) { 
  name = who.inject( '' ) { String s, String c ->
    s += s ? c.toLowerCase() : c.toUpperCase()
  }
}

As metioned in the comments,

Greet( String who ) { 
  name = who.capitalize()
}

is the proper way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!