vendredi 6 novembre 2020

invoking method that takes string array as parameter results in IllegalArgumentException

I'm using runtime reflection to load a class which contains the following two methods:

public static void foo(int[] args)
{
    System.out.print("foo invoked: ");
    for(int arg : args)
        System.out.print(arg + " ");
    
    System.out.println();
}

public static void bar(String[] args)
{
    System.out.print("bar invoked: ");
    for(String arg : args)
        System.out.print(arg + " ");
    
    System.out.println();
}

(identical methods except one takes an int array and the other takes a string array)

I then attempt to invoke the two methods like so:

    int[] intArr = {1,2,3};
    clazz.getMethod("foo", int[].class).invoke(null, intArr);

    String[] strArr = {"1","2","3"};
    clazz.getMethod("bar", String[].class).invoke(null, strArr); //Exception

(here 'clazz' is the class the two methods reside in, which i have loaded at runtime)

The first invocation causes no exceptions and outputs the expected output, but the second invocation throws the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at ReflectionTests.main(ReflectionTests.java:63)

Why is this?





Aucun commentaire:

Enregistrer un commentaire