import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* (一切从接口开始)
* @author 硬度
*
*/
interface Movable {
void move(int speed);
}
/**
* 坦克类
*
* @author 硬度
*
*/
class Tank implements Movable {
@Override
public void move(int speed) {
System.out.println("Tank moving(speed=" + speed + ") ...");
}
}
/**
* 实现申请
*
* @author 硬度
*/
class TankSuperMoving implements InvocationHandler {
private Movable tank;
/**
* 绑定代理实体
* @param movable 是实体(不是接口)
* @return 实现代理
*/
public Object bind(Movable tank) {
this.tank = tank;
return Proxy.newProxyInstance(Tank.class.getClassLoader(),
Tank.class.getInterfaces(), this);
}
/**
* 这个是必须实现滴
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("move")) { // 嗯,只不过要改动move方法
System.out.println("Tank super moving ...");
/*
* return 如果不用调原move方法,这里应该直接返回
*/
}
return method.invoke(tank, args); // 如果还需要调用原方法
}
}
/**
* 测试一下喽
* @author 硬度
*
*/
public class TestProxy {
public static void main(String[] args) {
Movable tank = (Movable) new TankSuperMoving().bind(new Tank());
tank.move(10);
}
}
转载于:https://www.cnblogs.com/lpdirect3d/p/3466753.html