Java实现代理模式(CGLIB)

先用你喜欢的方式加上依赖,我以maven为例:

<dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib</artifactId>
     <version>2.2.2</version>
</dependency>

真实角色:

public class Hello {
    public void hello() {
        System.out.println("My Hello.");
    }
}

代理角色:

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/** * Created by dubby on 16/4/26. */
public class HelloProxy implements MethodInterceptor {

    Hello hello = null;

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("proxy");
        return methodProxy.invokeSuper(o, objects);
    }
}

测试:

import net.sf.cglib.proxy.Enhancer;

/** * Created by dubby on 16/4/26. */
public class Test {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();

        enhancer.setCallback(new HelloProxy());
        enhancer.setSuperclass(Hello.class);
        Hello hello = (Hello) enhancer.create();
        hello.hello();
    }

}

对于final方法无法代理。

CGLIB还提供了一个过滤器的工具,可以用来选择,哪一个方法用哪一个代理类来代理。
再来一个代理类:

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/** * Created by dubby on 16/4/26. */
public class HiProxy implements MethodInterceptor {
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("hi");
        return methodProxy.invokeSuper(o,objects);
    }
}

加上一个过滤器

import net.sf.cglib.proxy.CallbackFilter;

import java.lang.reflect.Method;

/** * Created by dubby on 16/4/26. */
public class HelloFilter implements CallbackFilter {
    public int accept(Method method) {
        if("hello".equals(method.getName()))
            return 0;
        return 1;
    }
}

为什么是int呢?因为你可以有很多歌代理类选择,看下面吧:

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

/** * Created by dubby on 16/4/26. */
public class Test {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();

        enhancer.setCallbacks(new Callback[]{new HelloProxy(), new HiProxy()});//上面的过滤器里的返回值代表这里的回调代理类的位置
        enhancer.setSuperclass(Hello.class);
        enhancer.setCallbackFilter(new HelloFilter());
        Hello hello = (Hello) enhancer.create();
        hello.hello();
        hello.hi();
    }

}

试试吧。

你可能感兴趣的:(java,cglib,代理模式)