Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke method with an array parameter using reflection

I am attempting to write a method the executes a static method from another class by passing an array of strings as arguments to the method.

Here's what I have:

public static void
executeStaticCommand(final String[] command, Class<?> provider)
{
    Method[] validMethods = provider.getMethods();

    String javaCommand = TextFormat.toCamelCase(command[0]);

    for (Method method : validMethods) {
        if (method.getName().equals(javaCommand)) {
            try {
                method.invoke(null, new Object[] { new Object[] { command } });
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                Throwable ex = e.getCause();
                ex.printStackTrace();
            }
            break;
        }
    }
}

Such that this:

String[] args = new String[] { "methodName", "arg1", "arg2" }; 
executeStaticCommand(args, ClassName.class);

Should execute this:

public class ClassName {
    public static void methodName(String[] args) {
        assert args[1].equals("arg1");
    }
}

However I'm getting IllegalArgumentExceptions.

like image 886
azz Avatar asked Apr 11 '13 14:04

azz


People also ask

How do you call a method using an array of objects in Java?

Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

What is reflection array?

In telecommunications and radar, a reflective array antenna is a class of directive antennas in which multiple driven elements are mounted in front of a flat surface designed to reflect the radio waves in a desired direction.


1 Answers

You have two problems:

  1. The target parameter type is String[], but you're passing in a Object[]
  2. You're passing in the whole command array as arguments, which includes the method name

The problems are all in the inner try block, so I show only that code.

String[] args = Arrays.copyOfRange(command, 1, command.length - 1);
method.invoke(null, new Object[]{args}); // must prevent expansion into varargs

Thanks to Perception for reminding me of the varargs issue

like image 55
Bohemian Avatar answered Sep 27 '22 21:09

Bohemian