ApectJ的原理和使用

ApectJ的原理和使用

大鱼 6,977 2019-05-14

1. 简介

Aspect Oriented Programming(AOP)面向切面编程是目前比较流行的一种编程方式。android端引入比较插件麻烦,可以采用
https://github.com/HujiangTechnology/gradle_plugin_android_aspectjx

2. 原理

通过预编译方式和运行期动态代理实现不修改源代码,就给程序动态统一添加功能,直白点说就是插桩。
97423524afad842e344a148.png

简单示例

@Aspect
class InheritAspect {
    private companion object {
        private const val TAG = "InheritAspect"
        private const val ON_CREATE_EXECUTION = "execution(void *..*Activity.onCreate(..))"
    }
 
    @Pointcut(ON_CREATE_EXECUTION)
    fun onCreateExecution() {
    }

    @Before("onCreateExecution()")
    fun beforeOnCreateExecution(joinPoint: JoinPoint) {
        Log.i(TAG,"onCreate start")
    }
}

反编译后

//源代码
protected void onCreate(@Nullable Bundle var1) {
   super.onCreate(var1);
}
//运行后
protected void onCreate(@Nullable Bundle var1) {
   JoinPoint var2 = Factory.makeJP(ajc$tjp_7, this, this, var1);
   //拿到InheritAspect的单例对象
   InheritAspect.aspectOf().beforeOnCreateExecution(var2);
   super.onCreate(var1);
}

3. 使用

1.支持的连接点(JoinPoint) --> 程序中可以插入代码的地方
974235242c99d98f3bc0291.png
2. 表达式

 {注解}{修饰符}<返回值>{类}<方法名><方法参数> 
 {}为可选项 

a> 可以通过使用&&、||、!操作符进行逻辑关系组合
b> JoinPoint提供this属性,代表当前AOP代理对象

call(* action(..))&&this(AspectJActivity)
相当于插入了
if(xxx instanceof AspectJActivity){//执行插入代码段}

c> 连接点JoinPoint提供了args,用来约束实参的类型

execution(* a(Context+))&&args(Activity)

d>还有target、within 不常用

  1. 注解支持
    (1)@this/@target/@within/@args分别对应上面的几个表达式
    (2)@annotation, 可以通过自定义or系统的注解来过滤,例如
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LoginFilter {
    ...
}

@LoginFilter()
public UserInfo getUserInfo() {
  ...
}

@PointCut(@annotation(com.richard.kaishustory.aop.LoginFilter))
public void onNeedLoginPoint(){}

@Around("onNeedLoginPoint")
public void onNeedLoginHook(final ProceedingJoinPoint) {
  ...
}

  1. JoinPoint类参数说明
/**
 * this:AOP代理对象
 * target:目标对象
 * args:参数类型列表
 * signature.methodName:连接点的方法名
 * signature.declaringTypeName:连接点的方法属于的类型(编译时类型)
 * sourceLocation.withinType:连接点声明类(编译时类型)
 * sourceLocation.fileName:调用连接点方法的源码文件
 * sourceLocation.line:调用连接点方法的源码的行数
 */
fun showJoinPoint(joinPoint: JoinPoint, tag: String = "JoinPoint") {
    val thisObj = "this:${joinPoint.`this`?.javaClass?.name ?: "no"}\n"
    val targetObj = "target:${joinPoint.target?.javaClass?.name ?: "no"}\n"
    val args = "args:${joinPoint.args?.map { it?.javaClass?.name ?: "no" } ?: "no args"}\n"
    val methodName = "methodName:${joinPoint.signature.name}\n"
    val declareType = "declareType:${joinPoint.signature.declaringTypeName}\n"
    val withinType = "withinType:${joinPoint.sourceLocation.withinType?.name ?: "no within type"}\n"
    val sourceLocation = "sourceLocation:${joinPoint.sourceLocation.let { "${it.fileName}-${it.line}" }}\n"
}

ProceedingJoinPoint是JoinPoint的子类,多出来的是proceed()方法,用于执行切入点的源代码,该类型也是运行中实际创建的JoinPoint类型,before和after执行proceed没有意义,所以一般不用;而around一般用这个类型,用于执行源代码

  1. 运行时参数
    以上是插入代码方式,但是这还不够,因为我们很有可能在插入的代码中,去操作实际参数,甚至是this、target对象等,而我们现在的参数只有JoinPoint,这显然不够,需要拿到一些参数对象,举个栗子:
@Pointcut(value = "call(* *(..))&&this(activity)&&target(cat)&&args(value)", argNames = "activity,cat,value")
fun onPointCutCall(activity: AspectJActivity, cat: Cat, value: String) {
}

@Before(value = "onPointCutCall(activity,cat,value)", argNames = "activity,cat,value")
fun beforePointCutCall(joinPoint: JoinPoint, activity: AspectJActivity, cat: Cat, value: String) {
    //do with params
} 

4. 注意事项

a> 在类型匹配时,Number+,代表的是Number及其子类型,比如Double,Integer,但是不包括double,int,这些原始类型需要单独声明,比如int *(…)

b> 对于同一个切点,如果同时声明了@After和@Before,则不能声明@Around,会报错-编译器不能决定插入顺序;但是声明其中之一和@Around是可以的

c> 在匹配表达式中,如果父类的方法作为了切点,那么其子类重写的相应方法也会被作为切点,如果只想子类作为切点, 可以使用

execution(* com.richard.base.BaseActivity+.onCreate(**))

但是如果子类方法调用了super,则会两个都会切入
d> aspectj 容易与其他第三方库冲突,可以使用include只对需要内容插桩, or exclue 排除插桩三方库

aspectjx {
   //排除
	exclude 'android.support'
  //或者包括内容
        include 'com.richard.domain'
}