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

About Author

Author Image
Ankush Kocher

Ankush is a bright web app developer with expertise in Groovy and Grails development. Ankush is also an expert AngularJS developer.

Request for Proposal

Name is required

Comment is required

Sending message..