Groovy Dynamic Arguments

I wonder how it is possible in groovy to run an array of n elements.

Take a look at the snippet:

static void main(args){

    if (args.length < 2){
        println "Not enough parameters"
        return;
    }

    def tools = new BoTools(args[0])
    def action = args[1]

    tools."$action"(*args)

    System.exit(1)

}

      

As you can see, this is using a dynamic method call. The first 2 arguments are accepted as some configuration and method name, others that I would like to use as method parameters. So how can I do something like this:

tools."$action"(*(args+2))

      

Edited: If not possible in Java's native groovy syntax, it will do this:

def newArgs = Arrays.copyOfRange(args,2,args.length);
tools."$action"(*newArgs)

      

+3


source to share


1 answer


To remove items from the beginning args

, you can use the method drop()

. The original argument list does not change:

tools."$action"(*args.drop(2))

      



Another option, for example you are trying to access element N:

tools."$action"(*args[2..-1])

      

+3


source







All Articles