一般开发中使用较少。但是在使用一些框架时就比较常用。如 spring
what ?
与【动态代理】相对应是【静态代理】。
那什么是【静态代理】?个人的理解是:程序【运行前】已经存在的、编译好的代理类(代码)。
此时显而易见的就明白什么是【动态代理】了。程序运行前并不存在,需要在程序运行时,程序【实时地、动态地】生成(不需要手工编写代理类代码)。
why ?
为什么要使用动态代理呢?
若每个代理类只能为一个接口服务的话,实际开发中必然会产生过多的代理类。而这种方式明显是不推荐的,不可取的。
最好的办法是用尽量【少】的代理类完成全部的代理功能(一个代理类)。那么此时就必须使用到【动态代理】了。
当然动态代理的作用不仅仅只是减少代理类,这只是它最明显的作用。诸如在某个功能执行前后,需要进行额外处理方面完爆普通代理方面。
how ?
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @作者 Mitkey
* @时间 2016年3月17日 上午10:27:11
* @类说明:
* @版本 xx
*/
public class CommonInvocationHandler implements InvocationHandler {
private Object target;
public Object bind(Object target) {
this.target = target;
ClassLoader classLoader = target.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
return Proxy.newProxyInstance(classLoader, interfaces, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 执行前相关处理 TODO ...
this.doBefore();
Object result = method.invoke(this.target, args);
// 执行后相关处理 TODO ...
this.doAfter();
return result;
}
private void doAfter() {
// TODO Auto-generated method stub
System.out.println("CommonInvocationHandler.doAfter()");
}
private void doBefore() {
// TODO Auto-generated method stub
System.out.println("CommonInvocationHandler.doBefore()");
}
public interface IUserDao {
// ......
public boolean existUser(String uid);
// ......
}
public static class UserDaoImpl implements IUserDao {
@Override
public boolean existUser(String uid) {
// 模拟操作 TODO ...
return uid != null && !"".equals(uid);
}
}
public static void main(String[] args) {
CommonInvocationHandler invocationHandler = new CommonInvocationHandler();
IUserDao userDao = (IUserDao) invocationHandler.bind(new UserDaoImpl());
boolean existUser = userDao.existUser("mitkey");
System.err.println(existUser);
}
}
other
jdk 自带的动态代理是基于【接口】。若需要更强大的代理功能功能,可以考虑使用开源框架 【CGLib】