Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 298
whirlwin Avatar asked Apr 10 '12 11:04

whirlwin


People also ask

How do you pass null as an argument?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.

How is a method invoked with parameter?

The invoke () method of Method class Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters automatically to match primitive formal parameters.

How do you invoke a method on an object?

To invoke a static method using its MethodInfo object, pass null for obj . If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. The return value is null .


1 Answers

Try

method.invoke(new FooHolder(), new Object[]{ null }); 
like image 76
soulcheck Avatar answered Oct 07 '22 00:10

soulcheck