Call method via reflection when argument is of type Object[]
Asked Answered
P

2

6

I am using reflection to call a method on a class that is dynamically constructed at runtime:

public String createJDBCProvider(Object[] args)

Here's how:

Method m = adminTask.getClass().getMethod("createJDBCProvider", Object[].class);
id = (String) m.invoke(adminTask, new Object[]{ "a", "b", "c" });

IDEA warns me that I'm guilty of redundant array creation for calling varargs method.

The method I'm calling actually takes an Object[], not Object ... but they're probably equivalent and interchangeable I think, so I forge ahead.

At runtime I get:

java.lang.IllegalArgumentException: wrong number of arguments

So it seems that, perhaps, my Object[] is being passed as a sequence of Objects. Is this what is happening? If so, how can I coerce it to not do so?

Plaint answered 7/3, 2012 at 4:19 Comment(2)
What do you put in place of the ... in the actual code is the most relevant part. Could you please show what's in your real code?Cursorial
Varargs in Java is just syntactic sugar. The compiler turns Object... into Object[]. So yeah, they are equivalent.Hardesty
C
6

The way you are calling the method, the reflection thinks that you are passing three individual parameters, rather than a single array parameter. Try this:

id = (String) m.invoke(adminTask, new Object[]{ new Object[] {"a", "b", "c"} });
Cursorial answered 7/3, 2012 at 4:28 Comment(1)
Ack, I thought of trying this but didn't because it seemed too unlikely. Thanks.Plaint
T
1

Try this:

Method m = adminTask.getClass().getMethod("createJDBCProvider", Object[].class);
id = (String) m.invoke(adminTask, new String[]{ "a", "b", "c" });

The signature of the method invoke is public Object invoke(Object obj, *Object... args*) and Idea has an inspection that triggers when passing an array when a vararg of the same type is expected instead.

Tipster answered 10/8, 2012 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.