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?
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.
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.
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 .
Try
method.invoke(new FooHolder(), new Object[]{ null });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With