标签:
Java提供的动态代理,是“代理模式”的一个实现。代理模式简介:http://www.cnblogs.com/endlu/p/5169749.html
public class End implements People{ public void say(String s) { System.out.println("end is saying : " + s); } } public interface People { public void say(String s); } public class EndInvokeHandler implements InvocationHandler { private People p; public EndInvokeHandler(People p) { this.p = p; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before end say, gusse he will say : " + (String) args[0]); method.invoke(p, args); System.out.println("after end say"); return null; } } public class TestDynamicProxy { public static void main(String[] args) { End end = new End(); EndInvokeHandler handler = new EndInvokeHandler(end); Class aClass = end.getClass(); People people = (People) Proxy.newProxyInstance(aClass.getClassLoader(), aClass.getInterfaces(), handler); people.say("hahaha!"); } }
输出:
before end say, gusse he will say : hahaha! end is saying : hahaha! after end say
public class End { public void say(String s) { System.out.println("end is saying : " + s); } } public class EndInteceptor implements MethodInterceptor { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("before say, i guess he will say : " + objects[0]); methodProxy.invokeSuper(o, objects); System.out.println("after end say"); return null; } } public class TestCglib { public static void main(String[] args) { End end = new End(); EndInteceptor inteceptor = new EndInteceptor(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(end.getClass()); enhancer.setCallback(inteceptor); End endProxy = (End) enhancer.create(); endProxy.say("hello"); } }
输出:
before say, i guess he will say : hello end is saying : hello after end say
其中MethodInterceptor与jdk中的InvocationHandler是一样的功能。在里面调用被代理的方法时,注意是用方法代理MethodProxy的invokeSuper方法。
由于cglib基于继承机制,所以也有他的限制:不能是final类,final方法也不能被代理。
标签:
原文地址:http://www.cnblogs.com/endlu/p/5171546.html