Java反射机制的应用例子


目标:用一个代理类实现两个相似类的调用
1.两个相似类
Man类


Women类


代理类:
package Reflect;

import java.lang.reflect.Method;

public class Person {           //代理类

     private Object target; //目标对象  
     private String methodName; //目标方法  
     private Object[] params;    //参数数组
     private Method method;

   public Object getTarget() {
    return target;
   }

   public void setTarget(Object target) {
    this.target = target;
   }

   public String getMethodName() {
    return methodName;
   }

   public void setMethodName(String methodName) {
    this.methodName = methodName;
   }

   public Object[] getParams() {
    return params;
   }

   public void setParams(Object[] params) {
    this.params = params;
   }

   public Person(){
   
   }
  
   /**
      * _重新设置目标方法
      */
     private void reSetMethod(String methodName){
     if(params!=null){ //目标方法有参数
     int paramsLength = params.length;
     Class<?>[] paramsTypes = new Class<?>[paramsLength];
     for(int i=0;i<paramsLength;i++){
        paramsTypes[i] = params[i].getClass();
     }
     try {
        method = target.getClass().getMethod(methodName,paramsTypes);
    } catch (SecurityException e) {
     e.printStackTrace();
    } catch (NoSuchMethodException e) {
     e.printStackTrace();
    }
     }
     else //目标方法参数为null
     {
        try {
         method = target.getClass().getMethod(methodName,null);
     } catch (SecurityException e) {
      e.printStackTrace();
     } catch (NoSuchMethodException e) {
      e.printStackTrace();
     }
     }
    
     }
    
     /**
      * _重新设置目标对象和方法
      */
     private void reSetTarget(Object target,String methodName){
     this.target = target;
     this.reSetMethod(methodName);
     }
    
     /**
      * _动态调用已绑定方法
      */
     public void doMethod() throws Exception{
     reSetTarget(target,methodName);
     this.method.invoke(target, params);
     }
}


调用示例:

相关内容