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

后端 未结 4 789
臣服心动
臣服心动 2021-02-02 07:32

I am trying to invoke this method in Java reflectively:

public void setFoo(ArrayList foo) { this.foo = foo; }

The problem is that

相关标签:
4条回答
  • 2021-02-02 08:08

    Try

    method.invoke(new FooHolder(), new Object[]{ null });
    
    0 讨论(0)
  • 2021-02-02 08:08

    For me, this DOES NOT work:

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

    BUT this works:

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

    0 讨论(0)
  • 2021-02-02 08:22

    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. Only because you pass a single parameter, which could be interpreted as an object array itself, does method.invoke( obj, null) fail.

    If for example your method had two parameters, method.invoke( obj, null, null) would work perfectly fine.

    However if your method has a single Object[] parameter, you always have to wrap it.

    0 讨论(0)
  • 2021-02-02 08:30

    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(new FooHolder(), arg);
    
    0 讨论(0)
提交回复
热议问题