JDK动态代理理解
public class Main_ProxyJDK {
public static void main(String[] args) {
Tank tank = new Tank();
System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles","true");
Moveable proxyInstance = (Moveable) Proxy.newProxyInstance(Tank.class.getClassLoader(),
new Class[]{Moveable.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理开始了");
Object o = method.invoke(tank, args);
System.out.println("代理结束了....");
return o;
}
});
proxyInstance.move();
}
}
class Tank implements Moveable {
@Override
public void move(){
System.out.println("=============");
try {
Thread.sleep(new Random().nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
interface Moveable{
void move();
}