Java利用反射调用方法

时间:2025-03-10 18:43:06
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 * */ //实现代码 public class UserServletReflect { public <T> Object shoutObject(HttpServletRequest request,HttpServletResponse response,String type,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与方法是否有相对应的,没有就重定向到页面 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(); } return null; } } 进行调用实现方法: //需要调用单前类的方法进行new实例化给到shoutObject的参数T UserServlet us=new UserServlet(); //对反射方法进行调用 UserServletReflect usr = new UserServletReflect(); usr.shoutObject(request, response, type, us);