Tank实现Moveable接口,其中有一个move方法
public class Tank implements Movable{
public void move(){
方法体
}
}
我们想在Tank的move方法体前后加上自己的逻辑
1.InvocationHandler---- 方法调用的处理器
public interface InvocationHandler {
public void invoke(Object o,Method m);
}
2.编写具体实现类如TimeHandler实现InvocationHandler
import java.lang.reflect.Method;
public class TimeHandler implements InvocationHandler {
private Object target;
public TimeHandler(Object target ){
super();
this.target=target;
}
public void invoke(Object o,Method m){ //o为代理对象
代理的内容;//自己的逻辑
m.invoke(target,new Object[]{});//对带有指定的参数的指定的对象o调用由Mtehod对象m表示的底层方法。如果底层方法为静态的,那么可以忽略指定的object参数,该参数可以为null,返回方法m返回的值
代理的内容;
}
}
3.实现代理:
public calss Client{
public static void main (String[] args) throws Exception{
Tank t = new Tank();//代理的对象
InvocationHandler h=new TimeHandler(t);//自己定义的代理处理逻辑处理t对象
Moveable m = (Moveable)Proxy.newProxyInstance(Moveable.getClass().getClassLoader(),Moveable.getClsss().getInterface(),h);
m.move();
}
}
代理方法的实现:代理实现的接口中有哪些方法,代理中就有这些方法,调用代理中的每一个方法在调用的时候,都会将方法自身传递给InvocationHandler,同时将代理对象,方法参数传给InvocationHandler,InvocationHandler会调被代理对象的相应方法加附加的逻辑。