java的动态代理可分为:
1. JDK的动态代理。
a: 涉及Proxy和InvocationHandler两个类。
b: 需要目标类实现接口。
2. cglib的动态代理。
a: 需要引入第三方的cglib-2.1.3.jar包。
b:涉及Enhancer和MethodInterceptor两个类。
c: 原理是动态的给目标类构建一个子类,来代理目标类,所以无法代理声明为final的目标类。
-------------------------------------------------------------------------------jdk动态代理--------------------------------------------------
Person.java
package proxy.jdk; public interface Person { void show(String str); }
package proxy.jdk; public class Father implements Person { @Override public void show(String str) { System.out.println("This is Father"); } }
package proxy.jdk; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class PersonProxy implements InvocationHandler { Object target; public Object bind(Object target) { this.target = target; // 取得代理对象 return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("先做些准备工作"); Object result = method.invoke(target, args); System.out.println("扫尾工作"); return result; } }Test.java
package proxy.jdk; public class Test { public static void main(String[] args) throws Exception { PersonProxy proxy = new PersonProxy(); Person person = (Person)proxy.bind(new Father()); person.show("代理"); } }
-----------------------------------------------------------------------------------------------------cglib动态代理------------------------------------
Father.java
package proxy.cglib; public class Father { public void show() { System.out.println("cglib 动态代理 this is father"); } }
package proxy.cglib; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * 需要导入cglib-2.1.3.jar * @author xiongwenhua * */ public class PersonProxy implements MethodInterceptor { Object target; public Object bind(Object target) { this.target = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); // 回调方法 enhancer.setCallback(this); // 创建代理对象 return enhancer.create(); } @Override public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("事物开始"); proxy.invokeSuper(object, args); System.out.println("事物结束"); return null; } }Test.java
package proxy.cglib; public class Test { public static void main(String[] args) { PersonProxy proxy = new PersonProxy(); Father father = (Father)proxy.bind(new Father()); father.show(); } }