在Java的java.lang.reflect包下提供了一个Proxy类和一个InvocationHandler接口。通过这个类和接口可以生成JDK动态代理类或动态代理对象。

JDK动态代理例子:

// 抽象主题角色
public interface Sleep {
void sleep();
} // 真实主题角色
public class SleepImpl implements Sleep {
@Override
public void sleep() {
System.out.println("熟睡中");
}
} //动态处理器
public class DynamicProxyHandler implements InvocationHandler {
private Object obj ;
public DynamicProxyHandler(final 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 null;
}
}
//测试代码
public class ProxyTest {
public static void main(String[] args) {
Sleep sleep = new SleepImpl();
DynamicProxyHandler dph = new DynamicProxyHandler(sleep);
Sleep sleepProxy = (Sleep) Proxy.newProxyInstance(sleep.getClass().getClassLoader(),
sleep.getClass().getInterfaces(), dph);
sleepProxy.sleep();
}
} 结果:睡觉前要刷牙
熟睡中
睡醒后要吃早饭

JDK动态代理源码分析:

生产代理类主要是通过:Proxy.newProxyInstance方法:

@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h); final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
} /*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs); /*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
} final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}

最新文章

  1. Objective-C开发编码规范【转载】
  2. 5种io模式
  3. XmlDocument解析Soap格式文件案例:
  4. 【BZOJ 2820】YY的GCD
  5. Linux分区练习(1)
  6. CSS3参考手册
  7. p范数(p norm)
  8. Selenium2Library系列 keywords 之 _SelectElementKeywords 之 get_selected_list_value(self, locator)
  9. Web内容禁止选中的两种方式
  10. Linux 之 rsyslog 系统日志转发(转载)
  11. C# Best Practices - Define Proper Classes
  12. Java多线程-实例解析
  13. cookie 和 session的区别
  14. UIDatePicker在swift中的使用
  15. SHA256withRSA证书签名,私钥签名/公钥验签
  16. 从零开始学java (五)接口与内部类
  17. Apktool编译找不到“keyboardNavigationCluster”
  18. ubuntu 常见命令整理
  19. windows模糊查询指定进程是否存在
  20. (7)路由层的分发(不同app各自管理自己的和app的注册)

热门文章

  1. AlexeyAB DarkNet YOLOv3框架解析与应用实践(三)
  2. Pandas之:深入理解Pandas的数据结构
  3. Collection&amp;Map
  4. Redis的过期键删除策略
  5. 云原生时代的Java
  6. 『无为则无心』Python基础 — 3、搭建Python开发环境
  7. 《电容应用分析精粹:从充放电到高速PCB设计》最新勘误表
  8. golang中的defer和return的执行顺序
  9. 通过jquery创建节点以及节点属性处理
  10. 6、安装kvm虚拟机