How to change method name and argument list at Runtime Dynamically
Posted By : Ankush Kocher | 18-Nov-2014
In this blog we will see how to call a method and change the method name dynamically or can invoke a method even if we don't know the method name until it is invoked.
Consider, we have a domain class user which has fields username and we want to fetch an object from database, accordingly what we have name or id of user .
Domain class
class User{ String username static constraints = { username nullable: true } }
and in Controller......
class UserController{ def action(){ def mathodName = "" if(params.value.getClass() = "String"){ mathodName = "findByUsername" } else{ mathodName = "get" } def user = User.${mathodName}(value) [user:user] } }
So,we can change method name at runTime
and we can also "spread" the arguments in a method call, when we have a list of arguments :
e.g.
def maximum(int i1, int i2) { Math.max(i1, i2) } def numbers = [1, 2] maximum( *numbers ) == 2
This also works in combination of the invocation with a GString:
someObject."$methodName"(*args)
This is a simple example same can be achived by just calling method in condition but this can be more useful in some cases.
Thanks
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankush Kocher
Ankush is a bright web app developer with expertise in Groovy and Grails development. Ankush is also an expert AngularJS developer.