动态代理的作用:为对象提供代理以控制对对象的访问。
某些情况下,用户不想直接或者不能直接引用对象,而代理对象可以起到客户端和对象之间中介桥梁的作用。
在目前的Java开发包中包含了对动态代理的支持,但是其实现只支持对接口的的实现。
其实现主要通过是java.lang.reflect.Proxy类和java.lang.reflect.InvocationHandler接口。
Proxy类主要用来获取动态代理对象,InvocationHandler接口用来约束调用者实现。
业务接口:(JDB动态代理只能对实现了接口的实例进行代理)
public interface Person {
public void say();
public void look();
}
业务接口实现:
public class PersonImpl implements Person {
public void look() {
System.out.println("look.........");
}
public void say() {
System.out.println("say.........");
}
}
InvocationHandler实现,需要在接口方法调用前后加入一部份处理工作,这里仅仅在方法调用前后向后台输出两句字符串,其代码如下:
public class Handler implements InvocationHandler {
private Person person;
public Handler(Person person){
this.person = person;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("say")){
System.out.println("before say ..........");
}else if(method.getName().equals("look")){
System.out.println("before look .........");
}
method.invoke(person, args);
return null;
}
}
测试代码:
public static void main(String[] args) {
Person p = new PersonImpl();
Handler handler = new Handler(p);
Person pp = (Person) Proxy.newProxyInstance(p.getClass().getClassLoader(),
new Class[]{Person.class}, handler);
pp.look();
}