Friday, June 23, 2017

java: Reflection with array argument - java.lang.IllegalArgumentException: wrong number of arguments

For example, you have am arrayPrint method, which takes a String[] as its argument, in the Invoked class.

public class Invoked {
      public void arrayPrint(String[] items) {
            int i = 1;
            for (String item : items) {
                  System.out.println("Item "+ i ++ ": " + item);
            }
      }
}

Now, you want to call this arrayPrint method via reflection in the Invoker class.

public class Invoker {
      public static void main(String[] args) {
            String[] items = new String[3];
            items[0] = "Hello Dear!";
            items[1] = "So glad to see you.";
            items[2] = "How have you been?"

           Class invokedClass = Class.forName("Invoked");
           Method printMethod = invokedClass.getMethod("arrayPrint", String[].class);

           //This line will throw an Exception
           printMethod.invoke(new Invoked(), items);
     }
}

When it is executed, it throws the below exception.

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at test.Invoker.main(Invoker.java:29)

This exception occurs because the invoke method takes each element in the items array as a separate argument, therefore, in this case, there are three arguments in total. But the arrayPrint method only takes one argument.

To fix it:
Change the line above that gives the exception to this:

      printMethod.invoke(new Invoked(), new Object[] {items});

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.


No comments:

Post a Comment