Java代理
对于诸如以下代码,代理可以实现在不改变原有实现逻辑的情况下,对代码增加修饰内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public interface Subject { void request(); void hello(); }
public class RealSubject implements Subject {
@Override public void request() { System.out.println("real subject execute request"); }
@Override public void hello() { System.out.println("real subject execute hello"); } }
|
静态代理
以下为静态代理的实现方式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Proxy implements Subject { private RealSubject realSubject;
public Proxy(RealSubject realSubject) { this.realSubject = realSubject; }
@Override public void request() { System.out.println("before"); try { realSubject.request(); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("after"); } }
@Override public void hello() { realSubject.hello(); } }
|
动态代理
静态代理的缺点,每当
JDK实现动态代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
public class JdkProxySubject implements InvocationHandler { private RealSubject realSubject;
public JdkProxySubject(RealSubject realSubject) { this.realSubject = realSubject; }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); Object result = null; try { result = method.invoke(realSubject, args); } catch (Exception e) { e.printStackTrace(); throw e; } finally { System.out.println("after"); } return result; } }
|
CGLIB实现动态代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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 result = null; try { result = methodProxy.invokeSuper(obj, args); } catch (Exception e) { e.printStackTrace(); throw e; } finally { System.out.println("after in cglib"); } return result; } }
|