美文网首页
ApectJ的原理和使用

ApectJ的原理和使用

作者: 一夜游神 | 来源:发表于2020-08-16 11:24 被阅读0次

1. 简介

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

2. 原理

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


方法示意图

简单示例

@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) --> 程序中可以插入代码的地方


连接点
  1. 表达式
 {注解}{修饰符}<返回值>{类}<方法名><方法参数> 
 {}为可选项 

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'
}

相关文章

  • ApectJ的原理和使用

    1. 简介 Aspect Oriented Programming(AOP)面向切面编程是目前比较流行的一种编程方...

  • GCD的使用和原理

    在我们做iOS开发的过程中,经常会与多线程打交道,异步绘制,网络请求等,方式有NSThread,NSOperati...

  • Nginx的原理和使用

    nginx架构 nginx使用多进程的方式来工作,nginx启动后会有一个master进程和多个worker进程,...

  • Runtime的原理和使用

    Runtime的原理和使用 runtime简介 runtime简称运行时。OC就是运行时机制,其中最主要的是消息机...

  • JobScheduler的使用和原理

    1、JobScheduler的使用 1.1 简介 JobScheduler主要用于在未来某个时间下满足一定条件时触...

  • Block的原理和使用

    前言:最近看了好多block相关的东西,block在项目中很常见,想必大家也都比较熟悉,可是,细细想下,又有好多迷...

  • thrift 的原理和使用

    Thrift 架构 Thrift是一个跨语言的服务部署框架,最初由Facebook于2007年开发,2008年进入...

  • volatile的原理和使用

    1.对线程的可见性 Java的volatile关键字声明使变量对不同线程具有可见性。程序在多线程操作non-vol...

  • LiveData的使用和原理

    2.1.LiveData是google官方架构JetPack系列的一个响应式开发框架(响应式开发是一种专注于数据流...

  • ViewModel的使用和原理

    首先我们要知道ViewModel是什么?怎么用?内部怎么实现的?好处是什么? ViewModel 是一种用来存储和...

网友评论

      本文标题:ApectJ的原理和使用

      本文链接:https://www.haomeiwen.com/subject/kbewhktx.html