懵懵灯灯的BLOG

寒夜孤灯点点星

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  56 随笔 :: 10 文章 :: 22 评论 :: 0 Trackbacks
 1import java.lang.reflect.InvocationHandler;
 2import java.lang.reflect.Method;
 3import java.lang.reflect.Proxy;
 4
 5
 6public class MyProxy {
 7    
 8    public static void main (String[] args){
 9        BusinessInterface businessImpl=new BusinessImpl();
10        
11        InvocationHandler handler = new LogHandler(businessImpl);
12        
13        BusinessInterface proxy= (BusinessInterface) Proxy.newProxyInstance(
14                businessImpl.getClass().getClassLoader(),
15                businessImpl.getClass().getInterfaces(),
16                handler);
17        
18        proxy.processBusiness();
19        
20    }

21}

22
23interface BusinessInterface{
24    public  void processBusiness();
25}

26
27class BusinessImpl implements BusinessInterface{
28
29    public void processBusiness() {
30        // TODO Auto-generated method stub
31        System.out.println("Processing business logic ");
32    }

33}

34
35class LogHandler implements InvocationHandler {
36    
37    private Object delegate;
38    public LogHandler(Object delegate){
39        this.delegate=delegate;
40    }

41
42    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
43        // TODO Auto-generated method stub
44        Object o=null;
45        try{
46            System.out.println("INFO Begin ");
47            o=method.invoke(delegate, args);
48            System.out.println("INFO End ");
49        }
catch (Exception e){
50            System.out.println("INFO Exception ");
51        }

52        return o;
53    }

54}
这里用java.lang.reflect.Proxy实现动态代理类,在其中实现了在方法调用前和方法调用后的日志功能。
posted on 2008-02-27 12:50 懵懵灯灯 阅读(850) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: