Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 setParam(N ... n){
    System.out.println("Calling set param...");
}

Here's the invoking code :

try {
        Class<?> c = Class.forName("com.test.reflection.TestClass");
        Method  method = c.getMethod ("setParam", com.test.reflection.N[].class);
        method.invoke(c, new com.test.reflection.N[]{});

I'm getting IllegalArgumentException in the form of "wrong number of arguments" at the last line where I'm calling invoke. Not sure what I'm doing wrong.

Any pointers will be appreciated.

  • Thanks
like image 932
Shamik Avatar asked Jan 12 '12 23:01

Shamik


People also ask

What is method reflection in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is method parameter reflection in Java?

Overview. Method Parameter Reflection support was added in Java 8. Simply put, it provides support for getting the names of parameters at runtime. In this quick tutorial, we'll take a look at how to access parameter names for constructors and methods at runtime – using reflection.


1 Answers

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
like image 83
gorootde Avatar answered Sep 28 '22 00:09

gorootde