JDK动态代理

1、接口类

public interface UserDAO  {
  public void do(){};
}

2、实现类

public class UserDAOImp implements UserDAO{
    public void do(){
        System.out.println("do userDAO");
    }
}

3、要支入的方法的类

public static class Transaction{

    public void start(){
       System.out.println("Transaction start......");
    }
    public void end(){
      System.out.println("Transaction end......");
    }
}

4、Handler类

public class TransactionHandler implements InvocationHandler {   
    private Object target;   
    public TransactionHandler(Object target) {   
        this.target = target;   
    }   //也可以用getter 和setter方法
    public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {   
        Transaction.start();   
        Object obj = method.invoke(target, args);   
        Transaction.end();   
        return obj;   
    }   
} 

5、调用的类(客户端或者测试类)

import java.lang.reflect.Proxy; 
public class TestDynamicProxy { 
  public static void main(String[] args) { 
    UserDAO target = new UserDAOImp(); 
    Handler handler = new Handler(target);

    /**
    或者 Handler handler = new Handler();
           handler .setHandler(target);
    */
    UserDAO proxy = (UserDAO) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), handler); 
    proxy.do(); 
  } 
} 

 

posted @ 2013-04-03 16:45  自行车上的程序员  阅读(146)  评论(0编辑  收藏  举报