[英]How do I reflectively invoke a method with null as argument?
I am trying to invoke this method in Java reflectively:我试图反射性地调用 Java 中的这个方法:
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.问题是我想将 null 作为
null
传递,这样 foo 就变成了 null。
However, in the following approach it assumes that there are no arguments, and I get IllegalArgumentException
( wrong number of arguments
):但是,在以下方法中,它假定没有 arguments,并且我得到
IllegalArgumentException
( wrong number of arguments
):
method.invoke(new FooHolder(), null);
// -----------------------------^ - I want null to be passed to the method...
How is this accomplished?这是如何实现的?
Try尝试
method.invoke(new FooHolder(), new Object[]{ null });
For me, this DOES NOT work:对我来说,这不起作用:
m.invoke ( c.newInstance(), new Object[] { null } );
m.invoke ( c.newInstance(), new Object[] { null } );
BUT this works:但这有效:
m.invoke ( c.newInstance(), new Object[] { } );
m.invoke ( c.newInstance(), new Object[] { } );
The compiler warning should make you aware of the problem;编译器警告应该让你意识到这个问题;
The argument of type null should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object, Object...) from type Method.
类型 null 的参数应显式转换为 Object[],以便从类型 Method 调用可变参数方法 invoke(Object, Object...)。 It could alternatively be cast to Object for a varargs invocation
它也可以转换为 Object 以进行可变参数调用
You can fix it like this;你可以这样修复它;
Object arg = null;
method.invoke(new FooHolder(), arg);
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. Method.invoke()
声明为变量 arity function,这意味着通常您不需要显式创建 object 数组。 Only because you pass a single parameter, which could be interpreted as an object array itself, does method.invoke( obj, null)
fail.仅仅因为你传递了一个参数,它可以被解释为一个 object 数组本身,所以 method.invoke
method.invoke( obj, null)
失败了。
If for example your method had two parameters, method.invoke( obj, null, null)
would work perfectly fine.例如,如果您的方法有两个参数,
method.invoke( obj, null, null)
将工作得很好。
However if your method has a single Object[]
parameter, you always have to wrap it.但是,如果您的方法只有一个
Object[]
参数,则始终必须将其包装起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.