简介
本文介绍Spring的AOP的工具类:AopUtils。
用法大全
判断代理类型
// 判断是不是 Spring 代理对象 boolean isAopProxy() // 判断是不是 jdk 动态代理对象 isJdkDynamicProxy() // 判断是不是 CGLIB 代理对象 boolean isCglibProxy()
获取被代理对象的 class
// 获取被代理的目标 class Class<?> getTargetClass()
相关工具
AopContext
//获取当前对象的代理对象 Object currentProxy()
获得目标对象
没有现成的工具类,需要手写。
参考Spring的测试代码(AopTestUtils#getTargetObject),见:这里
内容是这样的:
@SuppressWarnings("unchecked") public static <T> T getTargetObject(Object candidate) { Assert.notNull(candidate, "Candidate must not be null"); try { if (AopUtils.isAopProxy(candidate) && candidate instanceof Advised) { Advised advised = (Advised) candidate; Object target = advised.getTargetSource().getTarget(); if (target != null) { return (T) target; } } } catch (Throwable ex) { throw new IllegalStateException("Failed to unwrap proxied object", ex); } return (T) candidate; } @SuppressWarnings("unchecked") public static <T> T getUltimateTargetObject(Object candidate) { Assert.notNull(candidate, "Candidate must not be null"); try { if (AopUtils.isAopProxy(candidate) && candidate instanceof Advised) { Advised advised = (Advised) candidate; Object target = advised.getTargetSource().getTarget(); if (target != null) { return (T) getUltimateTargetObject(target); } } } catch (Throwable ex) { throw new IllegalStateException("Failed to unwrap proxied object", ex); } return (T) candidate; }
请先
!