1. 新建TestServlet類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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); // 方法的實(shí)現(xiàn) } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } |
2. 建立需要自動(dòng)調(diào)用的類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?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. 啟動(dòng)服務(wù)器訪問:
http://127.0.0.1:8081/TestPrj/Test?className=com.yanek.test.Test&method=test&username=aspboy
控制臺(tái)輸出:
hello
aspboy
說明: 類com.yanek.test.Test類的 方法 public void test(HttpServletRequest request, HttpServletResponse response) 被執(zhí)行了.
反射機(jī)制是java中的重要功能,在框架設(shè)計(jì)中大量使用.
測(cè)試環(huán)境: tomcat6.0
以上這篇利用java反射機(jī)制實(shí)現(xiàn)自動(dòng)調(diào)用類的簡(jiǎn)單方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。