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