AOP面向切面編程

在項(xiàng)目中我們經(jīng)常遇見統(tǒng)計(jì)耗時(shí),統(tǒng)計(jì)是否被點(diǎn)擊等等需求,比如統(tǒng)計(jì)耗時(shí)通常的寫法就是在執(zhí)行的前后都加時(shí)間點(diǎn)。

public void sao(View view) {
        Log.d(TAG,mDateFormat.format(new Date()));
        long beagin = System.currentTimeMillis();
        SystemClock.sleep(3000);//假設(shè)這在執(zhí)行操作

        long end = System.currentTimeMillis();
        Log.d(TAG,(end - beagin)+"ms");
    }

面向?qū)ο笤O(shè)計(jì)講究單一性,這個(gè)方法不僅有邏輯操作還有耗時(shí)的統(tǒng)計(jì),代碼一旦較多就很難看。
我們就可以使用AOP(面向切面編程)來解決。使用AOP需要下載 aspectj

搭建AOP
在app/build.gradle中配置aspectj的路徑

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 = null
    if (variant.hasProperty('javaCompileProvider')) {
        //gradle 4.10.1 +
        TaskProvider<JavaCompile> provider =  variant.javaCompileProvider
        javaCompile = provider.get()
    } else {
        javaCompile = variant.hasProperty('javaCompiler') ? variant.javaCompiler : 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;
            }
        }
    }
}

在項(xiàng)目的build.gradle中配置aspectj

把下載的aspectjrt.jar拷貝進(jìn)libs目錄下,其他不需要

implementation files('libs/aspectjrt.jar')

環(huán)境搭建完畢,還是很簡單的。

寫一個(gè)簡單的demo
首先寫一個(gè)注解作為切點(diǎn)(就是標(biāo)記我需要在哪個(gè)地方使用AOP)我這里是在方法上使用

/**
 * 切點(diǎn)
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface BehaviorTrace {
    String value();
}

寫一個(gè)切面(就是拿到我們需要的方法后怎么處理,就在這里處理)

/**
 * 切面
 * <p>
 * 通過切點(diǎn)切下來之后在這里處理
 */
@Aspect
public class BehaviorAspect {
    private SimpleDateFormat mDateFormat = new SimpleDateFormat();

    /**
     * 找到添加有BehaviorTrace注解的方法
     * * * 表示所有含有BehaviorTrace注解的方法
     * ..表示方法的任意參數(shù)
     */
    @Pointcut("execution(@com.example.aopdemo.BehaviorTrace * *(..))")
    public void annoBehavior() {

    }

    @Around("annoBehavior()")
    public Object dealPoint(ProceedingJoinPoint point) throws Throwable {
        //處理找到的方法
        MethodSignature signature = (MethodSignature) point.getSignature();
        //拿到方法的BehaviorTrace注解
        BehaviorTrace behaviorTrace = signature.getMethod().getAnnotation(BehaviorTrace.class);
        //拿到注解里的值
        String value = behaviorTrace.value();
        Log.d("TAG", value + "使用時(shí)間" + mDateFormat.format(new Date()));

        long beagin = System.currentTimeMillis();
        //方法執(zhí)行時(shí)(找到注解對應(yīng)的方法,如 MainActivity中的 yao方法,這個(gè)方法正在執(zhí)行)
        Object object = point.proceed();//開始執(zhí)行方法
        //方法執(zhí)行完成
        long end = System.currentTimeMillis();
        Log.d("TAG", value + "消耗時(shí)間:" + (end - beagin));
        return object;
    }
}

\color{red}{@Pointcut} 設(shè)置需要切入的方法
@Around,@Before,@After 定義具體插入的代碼

使用就很簡單了



只需要在你想要的方法上添加一個(gè)注解就可以了。再也不用寫耗時(shí)統(tǒng)計(jì)相關(guān)的代碼了。

原理:
原本我們的java文件要生成class文件需要用到j(luò)avac.exe,aspectJ使用的自己的javaC文件把我們的java文件編譯成class文件,當(dāng)然它是遵守java的編譯規(guī)則的。
反編譯一下生成的class文件。

@BehaviorTrace("看見")
  public void yao(View view)
  {
    View localView = view; 
    JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this, localView);
    Object[] arrayOfObject = new Object[3];
    arrayOfObject[0] = this; arrayOfObject[1] = localView; 
    arrayOfObject[2] = localJoinPoint; 
    BehaviorAspect.aspectOf().dealPoint(new AjcClosure3(arrayOfObject).linkClosureAndJoinPoint(69648));
  }

在最后一句dealPoint調(diào)用的就是我們在切面里面實(shí)現(xiàn)的dealPoint方法,aspectOf()單例返回我們的BehaviorAspect對象。
而我們原有的代碼它會重新幫我們實(shí)現(xiàn)這個(gè)方法

static final void yao_aroundBody2(MainActivity paramMainActivity, View paramView, JoinPoint paramJoinPoint)
  {
    JoinPoint paramJoinPoint;
    View paramView;
    SystemClock.sleep(3000L);
    Log.d("TAG", "看見到美女啦");
  }

當(dāng)我們在dealPoint方法中調(diào)用point.proceed()的時(shí)候就會調(diào)用上面的方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容