使用reflect proxy

用reflect proxy把你的商业方法执行推迟,并放到其他地方执行。

概念:1.proxy instance  代理实例
     2.invocationHandler 调用处理器
编写商业对象和接口:
public interface BusinessInterface
{
 public void processBusiness();
}

public class BusinessObject implements BusinessInterface
{
 public void processBusiness(){
  System.out.println("this is the business code!");
 }
};

编写调用处理器,商业方法就在这里被调用:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class Myhandler implements InvocationHandler
{
 Object businessObject;
 Myhandler(Object delegate){
  businessObject = delegate;
 }
 public Object invoke(Object proxy , Method method , Object[] args) throws IllegalAccessException ,InvocationTargetException{
  Object o = null;
  System.out.println("log: start execute business");//这里可以用log4j,那么记录日志就和商业方法分开了
  //if(IsPermission(user)){//可以考虑在这里进行安全控制
   //Transaction.begin();//可以考虑在这里进行事务处理控制
   //long begin = System.CurrentTimeMillis();
   o = method.invoke(businessObject,args);//执行商业方法
   //long end = System.CurrenTimeMillis();
   //System.out.println(">>log:"+ (end - begin));//进行性能统计,
   //Transaction.commit();//
  //}
  System.out.println("log: end execute business");
  return o;
 }
};


构造代理实例并用代理实例来执行商业方法
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class AoP
{
 public static void main(String[] args)
 {
  BusinessInterface businessObject = new BusinessObject();
  //构造一个handler
  InvocationHandler handler = new Myhandler(businessObject);
  //构造代理实例
  BusinessInterface proxy = (BusinessInterface)Proxy.newProxyInstance(businessObject.getClass().getClassLoader(),businessObject.getClass().getInterfaces(),handler);
  //用代理实例来执行商业方法,那么代理会调用myhandler的invoke()来执行这个方法
  proxy.processBusiness();
 }
}

发布了53 篇原创文章 · 获赞 1 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章