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

I am trying to invoke this method in Java reflectively:

publicvoid 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(newFooHolder(),null);// -----------------------------^ - I want null to be passed to the method...

How is this accomplished?

解决方案:

1.Try

method.invoke(newFooHolder(),newObject[]{null});

2.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. It could alternatively be cast to Object for a varargs invocation

You can fix it like this;

Object arg =null;
method.invoke(newFooHolder(), arg);

 

 

posted on 2013-04-25 12:57  只愿软禁  阅读(261)  评论(0)    收藏  举报