java代理(三)--cglib动态代理

来源:互联网 发布:java员工请假系统 编辑:程序博客网 时间:2024/06/05 06:44

cglib动态代理是另一种动态代理,相对于jdk代理只适用于实现接口的代理,cglib动态代理可用于没有实现接口的代理。

cglib动态代理使用了asm字节码生成框架,动态生成代理类的字节码。

cglib动态代理涉及到的重要类是MethodInterceptor和Enhancer:

   MethodInterceptor是一个方法拦截接口,需要被实现,在方法intercept编写代理操作逻辑;

   Enhancer用于生成代理类字节码。

实例如下:

public class CglibProxyMain {    public static void main(String[] args) {        Enhancer enhancer = new Enhancer();        enhancer.setSuperclass(HelloService.class);        enhancer.setCallback(new HelloServiceInterceptor());        HelloService helloService = (HelloService)enhancer.create(); //创建代理类        helloService.hello("china");    }    //实现类    static class HelloService {        public void hello(String name) {            System.out.println("hello,"+name);        }    }    //代理拦截    static class HelloServiceInterceptor implements MethodInterceptor{        @Override        public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {            System.out.println("use cglib proxy");            Object result = methodProxy.invokeSuper(obj,args);            return result;        }    }}

原创粉丝点击