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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package com.shjlone.proxy;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;
public class ProxyClient {
public static void main(String[] args) { Shape realSubject = new Circle(); InvocationHandler handler = new DynamicProxy(realSubject); Shape subject = (Shape) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler); subject.draw(); } }
interface Shape { void draw();
}
class Circle implements Shape { @Override public void draw() { System.out.println("draw cicle"); } }
class DynamicProxy implements InvocationHandler {
private Object subject;
public DynamicProxy(Object subject) { this.subject = subject; }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(subject, args); }
}
|