AOP切面编程

一个分为4个步骤

1. 首先我们需要下载一个 aspectjrt.jar放在libs目录下然后在Moudle的gradle 中配置

dependencies{. implementation files('libs/aspectjrt.jar')}
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.8'
        classpath 'org.aspectj:aspectjweaver:1.8.8'
    }
}
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.8",
                         "-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;
            }
        }
    }
}

2.写一个注解类

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTrace {
    String value();
}

3. 

@Aspect
public class BehaviorTraceAspect {

    private static final String TAG = "BehaviorTraceAspect";

    // 定义切面的规则
   //  就是原来那些应用注释的地方要用到切面
   // execution(注释名 助使用的地方)
    @Pointcut("execution(@com.test.chenmiaojun.aoptest.annotion.BehaviorTrace * *(..))")
    public void methodAnnotatedWithBehaviorTrace(){}
    // 对进入切面的地方进行处理
    // @Around 在切入点前后都运行
    // @Before 在切入点之前运行
    // @After 在切入点之后运行
    @Around("methodAnnotatedWithBehaviorTrace()")
    public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String className = methodSignature.getDeclaringType().getName();
        String methodName = methodSignature.getName();
        String funName = methodSignature.getMethod().getAnnotation(BehaviorTrace.class).value();


        //  统计时间
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long duration = System.currentTimeMillis() - begin;
        Log.d(TAG, String.format("功能:%s,%s类的%s方法执行了,用时%d ms",funName,className,methodName,duration));
        return result;
    }
}

4 接下来就是使用

@BehaviorTrace("test")

可以看到 我们可以拿到这个方法的时间,方法名等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值