欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用java反射机制实现自动调用类的简单方法

程序员文章站 2024-03-13 13:28:03
1. 新建testservlet类 package com.yanek.test; import java.io.ioexception; impor...

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反射机制实现自动调用类的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。