1. 新建TestServlet类
package com.yanek.test;import java.io.IOException;import java.lang.reflect.Method;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取类的全路径以及名称 String className = request.getParameter("className"); // 获取方法名 String methodName = request.getParameter("method"); try { // 获取class文件 Class<?> t_class = Class.forName(className); // 获取该类所需求的方法 Method method = t_class.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.invoke(t_class.newInstance(), request, response);// 方法的实现 } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}
2. 建立需要自动调用的类
package com.yanek.test;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Test { /** * @param args */ public static void main(String[] args) { System.out.println("hello world !"); } public void test(HttpServletRequest request, HttpServletResponse response) { System.out.println("hello"); System.out.println(request.getParameter("username")); }}
3. web.xml配置
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://.yanek.test.Test类的 方法 public void test(HttpServletRequest request, HttpServletResponse response) 被执行了.
反射机制是java中的重要功能,在框架设计中大量使用.
测试环境: tomcat6.0
以上这篇利用java反射机制实现自动调用类的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。