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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With