import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class DemoMethodInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { System.out.println("before in cglib"); Object res = null; try { res = methodProxy.invokeSuper(obj,args); } catch (Exception e) { System.out.println("ex "+ e); throw e; } finally { System.out.println("after in cglib"); } return res; } }
import cn.evchar.proxy.aop.RealSubject; import cn.evchar.proxy.aop.Subject; import net.sf.cglib.proxy.Enhancer; public class Client { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); // 目標對象 enhancer.setSuperclass(RealSubject.class); // 織入代碼 enhancer.setCallback(new DemoMethodInterceptor()); // 生成 代理類 Subject subject = (Subject) enhancer.create(); subject.hello(); subject.request(); } }
一、JDK只能針對有接口的類的接口方法進行動態代理java
二、Cglib基於繼承來實現代理,沒法對static,final 類進行代理ide
三、Cglib基於繼承來實現代理,沒法對private,static 方法進行代理代理
四、反之JDK 不能對private 進行代理code