几个概念
目标对象:要被代理的对象 代理对象:proxy 调用处理器:InvocationHander
步骤
创建一个接口 创建该接口的实现类 创建实现类的实例对象 创建InvocationHander接口的实现类,在这个类中声明一个Object对象,构造方法或者set方法中传递一个目标对象, 用来初始化这个Object对象, 然后重写 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{}
方法,在这个方法中增强功能 通过Pxory的静态方法newProxyInstance(ClassLoaderloader, Class[] interfaces, InvocationHandler h)创建一个代理对象proxy, 参数为(类加载器, 目标对象实现的接口, 调用处理器) 使用proxy执行方法
案例
实现
public interface Sale {
void houseSell ( ) ;
}
public class HomeSeller implements Sale {
@Override
public void houseSell ( ) {
System. out. println ( "卖房:200万" ) ;
}
}
public class myInvocationHander implements InvocationHandler {
private Object obj;
public myInvocationHander ( Object obj) {
this . obj= obj;
}
@Override
public Object invoke ( Object proxy, Method method, Object[ ] args) throws Throwable {
System. out. println ( "中介接手卖房" ) ;
Object result= method. invoke ( obj, args) ;
System. out. println ( "中介完成卖房" ) ;
return result;
}
}
public class Main {
public static void main ( String[ ] args) {
Sale homeSeller= new HomeSeller ( ) ;
myInvocationHander hander= new myInvocationHander ( homeSeller) ;
Sale proxy= ( Sale) Proxy. newProxyInstance ( hander. getClass ( ) . getClassLoader ( ) , homeSeller. getClass ( ) . getInterfaces ( ) , hander) ;
proxy. houseSell ( ) ;
}
}