Alex Rivera | Logout

How do I reflectively invoke a method with null as argument?

Asked 2012-04-10T11:36:44.007
41

I am trying to invoke this method in Java reflectively:

public void setFoo(ArrayList<String> foo) { this.foo = foo; }

The problem is that I want to pass null as null, so that foo becomes null.

However, in the following approach it assumes that there are no arguments, and I get IllegalArgumentException(wrong number of arguments):

method.invoke(new FooHolder(), null);
// -----------------------------^ - I want null to be passed to the method...

How is this accomplished?

Edit
Report

1 Answer

5

A bit of an explanation to the solutions already posted.

Method.invoke() is declared as a variable arity function, and that means that normally you don't need to explicitly create an object array. Only because you pass a single parameter, which could be interpreted as an object array itself, does method.invoke( obj, null) fail.

If for example your method had two parameters, method.invoke( obj, null, null) would work perfectly fine.

However if your method has a single Object[] parameter, you always have to wrap it.

answered 2012-04-10T11:45:42.550

Your Answer