当前位置: 代码迷 >> 综合 >> Android AOP(Aspect Oriented Programming)简单用法
  详细解决方案

Android AOP(Aspect Oriented Programming)简单用法

热度:63   发布时间:2024-01-24 08:09:01.0

AOP:意为面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术
AspectJ是一个面向切面编程的框架,是对java的扩展且兼容java,AspectJ定义了AOP语法,它有一个专门的编译器来生成遵守java字节编码规范的Class文件。

实现原理:自定义注解+切面规则

/*** 用来表示性能监控*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTrace {String value();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserInfoBehaviorTrace {String value();
}
@Aspect
public class BehaviorTraceAspect {//定义切面的规则//1、就再原来的应用中那些注解的地方放到当前切面进行处理//execution(注解名   注解用的地方)@Pointcut("execution(@com.forest.dnjiagou.aop.annotation.BehaviorTrace *  *(..))")public void methodAnnottatedWithBehaviorTrace() {}//2、对进入切面的内容如何处理//@Before 在切入点之前运行
//    @After("methodAnnottatedWithBehaviorTrace()")//@Around 在切入点前后都运行@Around("methodAnnottatedWithBehaviorTrace()")public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();String className = methodSignature.getDeclaringType().getSimpleName();String methodName = methodSignature.getName();String value = methodSignature.getMethod().getAnnotation(BehaviorTrace.class).value();long begin = System.currentTimeMillis();Object result = joinPoint.proceed();SystemClock.sleep(new Random().nextInt(2000));long duration = System.currentTimeMillis() - begin;Log.d("forest", String.format("%s功能:%s类的%s方法执行了,用时%d ms",value, className, methodName, duration));return result;}
}

使用

//需要用到的方法@UserInfoBehaviorTrace("吃饭")@BehaviorTrace("吃饭")public void mShake(View view) {long begin = System.currentTimeMillis();SystemClock.sleep(new Random().nextInt(2000));long duration = System.currentTimeMillis() - begin;}@BehaviorTrace("音频")public void mAudio(View view) {}

结果:注解方法会被监听

  相关解决方案