protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//请求编码
request.setCharacterEncoding("utf-8");
//响应编码
response.setContentType("text/html;charset=utf-8");
//获取参数
String method = request.getParameter("method");
//利用反射动态调用方法
try {
//获取一个类对象
Class<?> clazz = Class.forName("Servlet.Servletcomplex");
//获取当前类public、protected和private修饰的方法
Method me = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
//修改java安全检查权限
me.setAccessible(true);
//执行方法
me.invoke(clazz.newInstance(),request,response);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
Servlet利用反射动态调用方法
最新推荐文章于 2020-12-04 12:29:07 发布