利用java反射机制实现自动调用类的简单方法
1.新建TestServlet类
packagecom.yanek.test; importjava.io.IOException; importjava.lang.reflect.Method; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassTestServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ //获取类的全路径以及名称 StringclassName=request.getParameter("className"); //获取方法名 StringmethodName=request.getParameter("method"); try{ //获取class文件 Class<?>t_class=Class.forName(className); //获取该类所需求的方法 Methodmethod=t_class.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(t_class.newInstance(),request,response);//方法的实现 }catch(Exceptione){ e.printStackTrace(); } } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doGet(request,response); } }
2.建立需要自动调用的类
packagecom.yanek.test; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassTest{ /** *@paramargs */ publicstaticvoidmain(String[]args){ System.out.println("helloworld!"); } publicvoidtest(HttpServletRequestrequest,HttpServletResponseresponse){ System.out.println("hello"); System.out.println(request.getParameter("username")); } }
3.web.xml配置
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="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/javaeehttp://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类的方法publicvoidtest(HttpServletRequestrequest,HttpServletResponseresponse)被执行了.
反射机制是java中的重要功能,在框架设计中大量使用.
测试环境:tomcat6.0
以上这篇利用java反射机制实现自动调用类的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。