import java.lang.reflect.InvocationTargetException;
public class Test {
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public void method3(){
System.out.println("method3");
}
public void method4(){
System.out.println("method4");
}
public void invokeMethod(String methodName) throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
this.getClass().getMethod(methodName, null) //null,参数类型的类class
.invoke(this, null);//this->new test(),null->参数(对应起来多个参数)
}
public static void main(String[] args) {
try {
new Test().invokeMethod("method1");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
网友评论