开发者

groovy variable function

开发者 https://www.devze.com 2022-12-28 06:58 出处:网络
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.

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..


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

service."fun${var}"()

The correct title is dynamic method invocation.

0

精彩评论

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

关注公众号