Monday, February 21, 2011

groovy variable function

I'm not even sure about how to title this qn. But, hope there is an easy way to do it in dynamic language like groovy.

say I have a class Service, where I delegate the business logic. the methods in it are funA(), funB()... funX().

Now I have a controller class, where I call the service closure, which can be invoked like service.funA() . Now based on a variable (which can have values A, B ... X), I need to cal the correct service closure. Basically to avoid writing lot of if conditional statements. Something like service."fun+var"() would do. I'm not sure whether it is possible to substitute variable in closure (function)name. or any way by passing function (name) as a parameter...not sure

I think PHP has a similar feature http://php.net/manual/en/functions.variable-functions.php

thanks for any pointer..

From stackoverflow
  • Yes, this is possible. This should do what you want:

    service."fun${var}"()
    

    The correct title is dynamic method invocation.

    bsreekanth : Thank you so much.. worked great

0 comments:

Post a Comment