AspectJ在kotlin环境集成以及异常处理

1.工程配置

1.在根工程build.gradle文件中配置

dependencies {
        ...
        classpath "com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.8"
        ...
    }

2.在module工程build.gradle文件中配置

plugins {
   ...
   id 'android-aspectjx'
}

异常处理:
在配置完上面代码可能出现以下异常

Kotlin 中使用AspectJ 遇到的 org.aspectj.apache.bcel.classfile.ClassFormatException
android {

   ......
   aspectjx {
        exclude 'versions.9'
    }
}

2.使用

1.定义注解类

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class CheckNet

2.定义AspectJ解析类

@Aspect
class PerformanceAspect {
 
    companion object {
        val TAG = PerformanceAspect::class.java.simpleName
    }
 
    @Pointcut("execution(@com.okay.kotlinaspect.CheckNet * *(..))")
    fun performancePointcut() {
    }
 
    @Around("performancePointcut()")
    @Throws(Throwable::class)
    fun measureMethodTime(joinPoint: ProceedingJoinPoint) {
        val signature = joinPoint.signature as MethodSignature
        val thisAny = joinPoint.`this`
        val className = thisAny.javaClass.simpleName
        val methodName = signature.method.name
        val start = System.currentTimeMillis()
        joinPoint.proceed()
        val duration = System.currentTimeMillis() - start
        Log.e(TAG, "$className.$methodName 耗时:${duration}ms")
    }
}

3.类中使用

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    @CheckNet
    fun click(view: View) {
        Toast.makeText(this,"点击了",Toast.LENGTH_SHORT).show()
    }
}

日志打印

2021-07-03 10:23:51.055 22136-22136/com.okay.kotlinaspect E/PerformanceAspect: MainActivity.click 耗时:18ms

完整工程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容