随笔 - 8, 文章 - 0, 评论 - 4, 引用 - 0
数据加载中……

2009年2月18日

Java静态代理和动态代理

网上和bolg上相关例子不少,今天自己动手写了个例子作为学习笔记。
首先java代理分为静态代理和动态代理,动态代理中java提供的动态代理需要动态代理一个inteface,如果没有inteface则需要使用实现cglib提供的接口。
下面例子只实现动态代理
public class MyProxy implements InvocationHandler{
    
    
static Object proxyObj = null;    
    
    
public static Object getInstance(Object obj){
        proxyObj
= obj;
        
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new MyProxy());
    }

    
    
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(
"使用代理..");
        
return method.invoke(proxyObj, args);
    }

}

实现方式
public static void main(String[] args) {
        ILeaveService service 
= (ILeaveService)MyProxy.getInstance(new LeaveServiceImpl());
        
try {
            service.listBizObjByHql(
"");
        }

        
catch (ServiceException e) {
            e.printStackTrace();
        }

    }

打印出:
使用代理..
query Hql..
使用Cglib
public class Test2 implements MethodInterceptor {
        
    
    
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println(
"cglib proxy");
        
return methodProxy.invokeSuper(obj, args);
    }

    
}

实现
public static void main(String[] args) {
        Enhancer enhancer 
= new  Enhancer();
        enhancer.setSuperclass(Test3.class);
        enhancer.setCallback(new Test2());        

        Test3 test 
= (Test3)enhancer.create();
        test.prinInfo(
"p.");
    }
输出
cglib proxy
p.
过滤器
public class Test4 implements CallbackFilter{

    
public int accept(Method method) {
        
if(method.getName().equals("method1")){
            
return 1;
        }
else if(method.getName().equals("method2")){
            
return 0;
        }

        
return 0;
    }

    
}
只有返回0的才执行(cglib中的NoOp.INSTANCE就是一个空的拦截器
    public static void main(String[] args) {        
        Callback [] callbacks 
= new Callback[]{new Test2(),NoOp.INSTANCE};
        Enhancer enhancer 
= new Enhancer();
        enhancer.setSuperclass(Test3.
class);
        enhancer.setCallbacks(callbacks);
        enhancer.setCallbackFilter(
new Test4());
        Test3 test3 
= (Test3)enhancer.create();
        test3.method1();
        test3.method2();
    }

    
}

执行结果
method1
cglib proxy
method2

posted @ 2009-02-18 16:52 Pitey 阅读(471) | 评论 (0)编辑 收藏