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

前端 未结 2 1743
庸人自扰
庸人自扰 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:39

    public class Test {
    
    public void setParam(N... n) {
        System.out.println("Calling set param...");
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        Test t=new Test();
        Class c = Class.forName("test.Test");
        Method  method = c.getMethod ("setParam", N[].class);
        method.invoke(t, (Object) new N[]{});
    }
    }
    

    Works for me.

    1. Cast your N[] to Object
    2. call invoke on instance, not on class

提交回复
热议问题