如何以null为参数反射调用方法?

whi*_*win 32 java reflection

我试图用Java反射调用这个方法:

public void setFoo(ArrayList<String> foo) { this.foo = foo; }
Run Code Online (Sandbox Code Playgroud)

问题是我想传递null null,因此foo变为null.

但是,在以下方法中,它假定没有参数,并且我得到IllegalArgumentException(wrong number of arguments):

method.invoke(new FooHolder(), null);
// -----------------------------^ - I want null to be passed to the method...
Run Code Online (Sandbox Code Playgroud)

这是如何完成的?

sou*_*eck 65

尝试

method.invoke(new FooHolder(), new Object[]{ null });
Run Code Online (Sandbox Code Playgroud)


Qwe*_*rky 7

编译器警告应该让你意识到这个问题;

类型为null的参数应该显式地转换为Object [],以便从类型Method调用varargs方法invoke(Object,Object ...).也可以将其转换为Object以进行varargs调用

你可以像这样修理它;

Object arg = null;
method.invoke(new FooHolder(), arg);
Run Code Online (Sandbox Code Playgroud)


Rui*_*ins 7

对我来说,这不起作用:

m.invoke(c.newInstance(),new Object [] {null});

但这有效:

m.invoke(c.newInstance(),new Object [] {});

  • 那么也许你有一个没有参数的方法 (3认同)

biz*_*lop 5

对已经发布的解决方案进行了一些解释.

Method.invoke()声明为变量arity函数,这意味着通常您不需要显式创建对象数组.只是因为传递一个参数(可能被解释为对象数组本身)才会method.invoke( obj, null)失败.

例如,如果您的方法有两个参数,那method.invoke( obj, null, null)将完全正常.

但是,如果您的方法只有一个Object[]参数,则始终必须将其包装起来.