/**
动态代理类使用到了一个接口InvocationHandler和一个代理类Proxy ,这两个类配合使用实现了动态代理的功能。
InvocationHandler 并实现它的invoke方法,然后再用Proxy的工厂方法newProxyInstance()创建一个代理对象,这个对象同样可以实现对具体类的代理功能。
而且想代理哪个具体类,只要给Handler(以下代码中的Invoker)的构造器传入这个具体对象的实例就可以了。
*/
接口InvocationHandler的方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
类Proxy的方法:
//获得具体类的代理
Proxy.newProxyInstance(
ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h
);
example:
//Invoker实现 InvocationHandler接口
public class Invoker implements InvocationHandler {
AbstractClass ac;
public Invoker(AbstractClass ac){
this.ac = ac;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//调用之前可以做一些处理
method.invoke(ac, args);
//调用之后也可以做一些处理
return null;
}
}
//创建具体类的处理对象
Invoker invoker1=new Invoker(new ClassA());
//获得具体类的代理
AbstractClass ac1 = (AbstractClass) Proxy.newProxyInstance(
AbstractClass.class.getClassLoader(),
new Class[] { AbstractClass.class }, invoker1
);
//调用ClassA的show方法。
ac1.show();
网友评论