Groovy: Metaclass - accessing instance methods -


i trying access method of instance using metaclass, error property not exist. there way access properties of classes declared in class.

here contrived example:

class dogfood {    def ft = 'food!'    def foodtype() { ft} }  class dog {   def bark() { println "woof!" }    dogfood df = new dogfood()   def ft() { println df.foodtype()}     def getdf() {     df   } }  def doaction( animal, action ) {   animal."$action"() }   def rex = new dog()  println rex.df.ft  //works  def barkstring = "bark"  doaction( rex, barkstring ) //works doaction( rex, "df.ft") //doesn't work doaction( rex, "getdf().ft") //does not work 

is there way access df.ft or getdf().getft() using groovy's metaclass methodology?

thanks in advance

i don't think can access . in string name using notation. can eval.x though.

def doaction( animal, action ) {     eval.x(animal, 'x.' + action) } 

edit: aware there risk involved in method if executing user input. can use eval execute arbitrary code. example,

groovy:000> foo = [bark: { println 'bark' }] ===> {bark=groovysh_evaluate$_run_closure1@db2e44d} groovy:000> eval.x(foo, 'x.bark()') bark ===> null groovy:000> eval.x(foo, 'x.bark(); println "executing more code"') bark executing more code groovy:000> 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -