AConsumer
AConsumer

Reputation: 2771

Unable to invoke the method with variable arguments using reflection in java

When the method m is ( where m is the method to be invoked using reflection )

public static Optional<JsonNode> concat(ObjectNode entity, String separator, String fieldName1,
          String fieldName2) 

Then i am able to get the computed value ( where computed value is the value obtained using reflection )

While, when the method m is

public static Optional<JsonNode> concat(ObjectNode entity, String ...separatorAndField)

then i am able not able to get the computed value

I am invoking the method as follows:-

   computedValue = (Optional<JsonNode>) m.invoke(null, methodArgs);

Note:- methodArgs is declared as an object array.

Upvotes: 0

Views: 39

Answers (1)

Michael
Michael

Reputation: 44090

Here's the difference between invoking a varargs and a non-varargs static method via reflection:

class Main
{
    public static void foo(String fieldName1, String fieldName2)
    {
        System.out.println(fieldName1 + "," + fieldName2);
    }

    public static void bar(String... fields)
    {
        System.out.println(String.join(",", fields));
    }

    public static void main(String[] args) throws Exception
    {
        final Method foo = Main.class.getMethod("foo", String.class, String.class);
        foo.invoke(null, "aaa", "bbb");

        final Method bar = Main.class.getMethod("bar", String[].class);
        bar.invoke(null, (Object) new String[] {"ccc", "ddd", "eee"});
    }
}

Output:

aaa,bbb
ccc,ddd,eee

Upvotes: 1

Related Questions