AOP 切面

博客介绍了在模块build.gradle中添加依赖,在项目build.gradle添加对应版本号,还提到自定义注解并将其加载到要检测的方法上,最后创建切面类并添加@Aspect注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 模块build.gradle添加依赖

implementation'org.aspectj:aspectjrt:1.9.4'

}

import org.aspectj.bridge.IMessage

import org.aspectj.bridge.MessageHandler

import org.aspectj.tools.ajc.Main



final def log = project.logger

final def variants = project.android.applicationVariants



//在构建工程时,执行编辑

variants.all { variant ->

    if (!variant.buildType.isDebuggable()) {

        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")

        return;

    }



    JavaCompile javaCompile = variant.javaCompile

    javaCompile.doLast {

        String[] args = ["-showWeaveInfo",

                         "-1.9",

                         "-inpath", javaCompile.destinationDir.toString(),

                         "-aspectpath", javaCompile.classpath.asPath,

                         "-d", javaCompile.destinationDir.toString(),

                         "-classpath", javaCompile.classpath.asPath,

                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]

        log.debug "ajc args: " + Arrays.toString(args)



        MessageHandler handler = new MessageHandler(true);

        new Main().run(args, handler);

        for (IMessage message : handler.getMessages(null, true)) {

            switch (message.getKind()) {

                case IMessage.ABORT:

                case IMessage.ERROR:

                case IMessage.FAIL:

                    log.error message.message, message.thrown

                    break;

                case IMessage.WARNING:

                    log.warn message.message, message.thrown

                    break;

                case IMessage.INFO:

                    log.info message.message, message.thrown

                    break;

                case IMessage.DEBUG:

                    log.debug message.message, message.thrown

                    break;

            }

        }

    }

}

 
  • 项目build.gradle中添加 版本号要对应
classpath 'org.aspectj:aspectjtools:1.9.4'
  • 自定义注解 annotation
    /**
    
     * 用来表示性能监控
    
     */
    
    @Target(ElementType.METHOD)
    
    @Retention(RetentionPolicy.RUNTIME)
    
    public @interface Behaviortrace {
    
        String value();
    
    }

     

  • 注解加载要检测的方法上
@Behaviortrace("摇一摇")

    public void yao(View view) {

//        long begin = System.currentTimeMillis();

        SystemClock.sleep(new Random().nextInt(2000));

//        long duration = System.currentTimeMillis() - begin;

//        Log.e("tp", "duration=="+duration);

    }

    @Behaviortrace("漂流瓶")

    public void piao(View view) {

        SystemClock.sleep(new Random().nextInt(2000));

    }

    @Behaviortrace("红包")

    public void hong(View view) {

        SystemClock.sleep(new Random().nextInt(2000));

    }
  • 创建切面BehaviortraceAspect类,类上面加@Aspect注解
@Aspect

public class BehaviotraceAspect {

    //定义切面规则

    //1、就在原来应用中那些注解的地方,到当前切面进行处理。

    //execution(注解名  注解用的地方) ,  * *(..) 任意类 任意方法(任意参数)

    @Pointcut("execution(@com.example.aop.annotation.Behaviortrace * *(..))")

    public void methodAnnotatedWithBehaviorTrace(){}

    //2、对进入切面的内容如何处理

    //@Before() 在切入点之前运行

    //@After()  在切入点之后运行

    //@Around() 在切入点前后都运行

    @Around("methodAnnotatedWithBehaviorTrace()")

    public Object weavJoinPoint(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.e("tp", String.format("%s功能:%s类的%s方法执行了,用时%d ms",

                value, className, methodName, duration));

        return result;

    }



}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值