Trick: Invoke methods with varargs

Two days ago I faced a strange situation:
Java: let’s say you have a main function (that, as you all know, accepts varargs arguments) and want to use it as a gateway for other main functions. You don’t want to specialize the gateway, so that it will work for any new subprogram your jar will have added. The gateway will receive, as first argument, the subprogram class name.
The first thing to do is easy:

 Class c = Class.forName(args[0]);

Next, we want a Method object for the “main” function:

Method mainMethod = c.getMethod("main",String[].class);

Next, we want to invoke the method but the thing shows up trickier than expected, because if you:

mainMethod.invoke(null, args); //NOT WORKING

Nope, nada. Why? Because the args you’re passing would be splitted in single arguments, that IS NOT what the function is expecting. In fact, “main” wants a “varargs”. That sounds like a nonsense, but varargs is in fact a little naive…
To workaround this:

Object o = args;
mainMethod.invoke(null, o); 
and there you go. This was not hard to solve, and thinking of it a little, it looks quite obvious, but the runtime error you get doing it the wrong way is a little too tricky, so I wanted to share this with you.
Peace
Follow

Get every new post delivered to your Inbox.