How to invoke method with variable arguments in java using reflection?

前端 未结 2 1740
庸人自扰
庸人自扰 2020-12-06 13:54

I\'m trying to invoke a method with variable arguments using java reflection. Here\'s the class which hosts the method:

public class TestClass {

public void         


        
2条回答
  •  天命终不由人
    2020-12-06 14:31

    There is no TestClass instance in your code snippet on which the methd is invoked. You need an instance of the TestClass, and not just the TestClass itself. Call newInstance() on c, and use the result of this call as the first argument of method.invoke().

    Moreover, to make sure your array is considered as one argument, and not a varargs, you need to cast it to Object:

    m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{});
    

提交回复
热议问题