当前位置:编程学习 > JAVA >>

Java“无关系”代理

package Proxy;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Manager {
 public void love(String boy,String girl)
 {
  System.out.println(boy+"\tlove\t"+girl);
 }
}
public class ManagerProxy {
 private Class clazz;
 private Object target;
 private Method method;
 private Object[]params;
 
 public ManagerProxy(Object target,String methodName,Object...params)
 {
  init(target,methodName,params);
 }
 public void init(Object target,String methodName,Object...params)
 {
  this.target=target;
  this.clazz=target.getClass();
  this.params=params;
  int paramsLenth=params.length;
  Class[]parms=new Class[paramsLenth];
  for(int i=0;i<paramsLenth;i++)
  {
   parms[i]=params[i].getClass();
  }
  try {
   this.method=clazz.getMethod(methodName,parms);
  } catch (SecurityException e) {
   System.out.println(e.getMessage());
  } catch (NoSuchMethodException e) {
   System.out.println(e.getMessage());
  }
 }
 
 public Object doMethod()
 {
  try {
   return this.method.invoke(target,params);
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
   return null;
  } catch (IllegalAccessException e) {
   e.printStackTrace();
   return null;
  } catch (InvocationTargetException e) {
   e.printStackTrace();
   return null;
  }
 }
 public static void main(String[]as)
 {
  Manager man=new Manager();
  ManagerProxy a=new ManagerProxy(man,"love","a","ss");
  System.out.println(a.doMethod());
 }
}
output: a  love ss
本文出自 “飞沙” 博客

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,