通过反射的思想来获取类方法
Class c = this.getClass();//获得当前类对象
Method = null;
try{
/**
*methodName 要调用的方法名
*HttpServletRequest.class 方法参数类型
*HttpServletResponse.class 方法参数类型
getMethod中只能有一个方法名,但是可以包含多个方法参数类型(类似数组)
*/
method = c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
}catch(Exception e){
throw new RuntimeException("您调用的方法不存在")
}
//调用类方法
try{
/**
*this 当前类对象
*req 方法参数
*resp 方法参数
invoke方法中只能包含一个类对象,和多个方法的参数(类似参数数组)
*/
method.invoke(this,req,resp);
}catch(Exception e){
throw new RuntimeException("您调用的方法"+methodName+",内部抛出异常!!!")
}
总结:当我们根据状态调用不同的方法时候可以考虑用这种方式来实现调用,这种设计可以提取到一个抽象类中,其它子类继承该方法,就可以在子类中自动调用该方法