Passing parameters dynamically into Method.Invoke
I have methods in a class
public class ReflectionClass {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String concatenate (String a, String b, String c){
return a + b + c;
}
}
I'm trying to call these methods through reflection. All I have in hand are - the method name and the parameters. Is there a way to pass the parameters into the Method.Invoke() method dynamically based on the number/type of parameters I have in hand?
正如你在文档中看到的public Object invoke(Object obj, Object... args)
需要一个varargs参数 - 所以你可以简单地传递一个参数数组。
You need to create an instance, get the methods, get the parameters, check the parameters by checking the type and how many... then call invoke depending of what
Example:
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("com.ReflectionClass");
Object obj = cls.newInstance();
for (Method m : cls.getDeclaredMethods()) {
if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(String.class)) {
String a = "A";
String b = "B";
String c = "C";
Object returnVal = m.invoke(obj, a, b, c);
System.out.println((String) returnVal);
} else if (m.getParameterCount() == 2 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
Object returnVal = m.invoke(obj, a, b);
System.out.println(returnVal);
} else if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
int c = 3;
Object returnVal = m.invoke(obj, a, b, c);
System.out.println(returnVal);
}
}
}
链接地址: http://www.djcxy.com/p/76510.html