public class DynamicProxy implements InvocationHandler {
Object proxied = null; //被代理的对象。
public DynamicProxy(Object proxied){
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(proxy.getClass().getSimpleName());
Object res = method.invoke(proxied,args);
// method.invoke(proxy,args);
System.out.println("do some thing after call the proxied object");
return res;
}
}
代理对象的获取
public class SimpleProxyDemo {
public static void main(String[] args) {
RealClass real = new RealClass();
real.doElseThing();
real.doSomething();
//在这里真正创建了代理队对象。
Interface inter = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class},
new DynamicProxy(real));
inter.doElseThing();
inter.doElseThing();
}
}