應用java反射機制完成主動挪用類的簡略辦法。本站提示廣大學習愛好者:(應用java反射機制完成主動挪用類的簡略辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是應用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反射機制完成主動挪用類的簡略辦法就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。