利用java反射机制实现自动调用类的简单方法
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://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>Test</description> <display-name>Test</display-name> <servlet-name>Test</servlet-name> <servlet-class>com.yanek.test.TestServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Test</servlet-name> <url-pattern>/Test</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <login-config> <auth-method>BASIC</auth-method> </login-config> </web-app>
4. 启动服务器访问:
http://127.0.0.1:8081/TestPrj/Test?className=com.yanek.test.Test&method=test&username=aspboy
控制台输出:
hello
aspboy
说明: 类com.yanek.test.Test类的 方法 public void test(HttpServletRequest request, HttpServletResponse response) 被执行了.
反射机制是java中的重要功能,在框架设计中大量使用.
测试环境: tomcat6.0
以上这篇利用java反射机制实现自动调用类的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)