优化前
switch(operate){
case "index":
index(request, response);
break;
case "add":
add(request, response);
break;
case "del":
del(request, response);
break;
case "edit":
edit(request, response);
break;
case "update":
update(request, response);
break;
default:
throw new RuntimeException("operate值非法");
}
优化后
//获取当前类所有的方法
Method[] methods=this.getClass().getDeclaredMethods();
for(Method m:methods){
//获取方法名
String methodName=m.getName();
if(operate.equals(methodName)){
try {
//找到和operate同名的方法,那么通过反射的技术调用它
m.invoke(this,request,response);
return ;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
throw new RuntimeException("operate值非法");