简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM