基于JDK的动态代理例子如下
接口 Subject
public interface Subject { public abstract void request(); }
实现类RealSubject
public class RealSubject implements Subject { @Override public void request() { System.out.println("from realsubjct"); } }
代理类
public class DynamicSubject implements InvocationHandler { private Object sub; public DynamicSubject(Object obj) { this.sub = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before calling: " + method); method.invoke(this.sub, args); System.out.println("after calling: "+method); return null; } }
客户端类
public class Client { public static void main(String[] args) { RealSubject rs = new RealSubject(); InvocationHandler handler = new DynamicSubject(rs); Class<?> cls = rs.getClass(); Subject subject = (Subject) Proxy. newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), handler); subject.request(); } }
执行结果
before calling: public abstract void com.learn.jvm.Subject.request() from realsubjct after calling: public abstract void com.learn.jvm.Subject.request()