转载:http://hi.baidu.com/pj1990zp/item/6eb860173dcd65486826bb0a?qq-pf-to=pcqq.c2c
Java 通过反射机制动态调用java类方法
public class ManyMethod {
public void method_1(){
System.out.println("这是方法:method_1");
}
public void method_2(){
System.out.println("这是方法:method_2");
}
public void method_3(){
System.out.println("这是方法:method_3");
}
public void method_4(){
System.out.println("这是方法:method_4");
}
public void method_5(String num){
System.out.println("接收到的参数:" + num);
}
}
import java.lang.reflect.Method;
public class DynamicCall {
public static void main(String[] args) throws Exception {
ManyMethod manyM = new ManyMethod();
Class extends ManyMethod> clazz = manyM.getClass();
String methodName = "method_";
for(int i = 1; i < 6; i++){
methodName = methodName + String.valueOf(i);
if(i != 5){
Method method = clazz.getDeclaredMethod(methodName);
method.invoke(manyM);
}else{
Method method = clazz.getDeclaredMethod(methodName, String.class);
method.invoke(manyM, "测试");
}
methodName = "method_";
}
}
}
输出:
这是方法:method_1
这是方法:method_2
这是方法:method_3
这是方法:method_4
接收到的参数:测试