java利用反射调用方法_Java利用反射调用方法

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

package com.ba.util;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* 思路分析:

* 1、创建一个shoutObject方法返回值为Object接收参数有:request、response、type、t

* 2、获取T该类公共成员的 Class 对象的数组

* 3、获取该类与指定名和参数相匹配的方法的 Method 对象数组,然后进行遍历,用getName()方法得到我们的 T 的所有方法

* 4、对jsp传过来的type与T的方法进行比较,如果相等,那么就拼接方法和参数,然后执行将结果返回即可

* @author Administrator

*

*/

//实现代码

publicclass UserServletReflect {

public ObjectshoutObject(HttpServletRequest request,HttpServletResponse response,Stringtype,T t){

try {

Class class1 = t.getClass();

Method[] methods =class1.getDeclaredMethods();

int count = 0;

for (int i = 0; i < methods.length; i++) {

//getName()以 String 形式返回此 Method 对象表示的方法名称。

if(methods[i].getName().equals(type)){

count++;

System.out.println( methods[i].getName());

//getMethod返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。

Method method1= class1.getMethod(methods[i].getName(),HttpServletRequest.class,HttpServletResponse.class);

//invoke()对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。

return method1.invoke(t,request,response);

}

}

//判断type与方法是否有相对应的,没有就重定向到index.jsp页面

if (count==0) {

Method method2 =class1.getMethod("rsr",HttpServletRequest.class,HttpServletResponse.class);

return method2.invoke(t,request,response);

}

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

returnnull;

}

}

进行调用实现方法:

//需要调用单前类的方法进行new实例化给到shoutObject的参数T

UserServlet us=new UserServlet();

//对反射方法进行调用

UserServletReflect usr = new UserServletReflect();

usr.shoutObject(request, response, type, us);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值