android 切面编程,Android 面向切面编程-aspjectj应用

1.为什么要用切面

随着业务越来越复杂,项目中的模块可能越来越多, 面向切面可以减少模块间的耦合,提高模块的复用率

2.aspjectj语法

android aop框架 有好几种,不过aspjectj应该算最成熟了,github上很多开源的也是基于这个框架的,先简单介绍下aspject语法

@After("execution(* com.vapi.test.MyTest.get**(..))")

public void onLibraryTestMethod(JoinPoint joinPoint) throws Throwable {

Log.e("helloAOP", "mytestlibrary:::" + joinPoint.getSignature());

}

从下面的join point 对应android 的代码可以看书, 主要是切面类型,普通方法或者构造器

point cut

call: 在织入方法处

execution: 在织入方法内

这两个的区别很容易理解, 比如a.b(),  call是在a.b()前后, execution 在b()内

within和target 匹配制定类型 可以是注解类型

@After("@within(com.lin.aopdemotest.anno.WithInMark)")

public void onTestWith(JoinPoint joinPoint) throws Throwable {

Log.e(TAG, "com.lin.aopdemotest.anno.WithInMark :::" );

}

advice

after,before: 织入前后

afterReturn, afterThrows:织入方法会报错的时候

around: 可以理解为直接替换方法, 在方法内自行决定处理被调用方法

Pointcut: 声明一个切面,后面after,before可以直接引用声明的切面,相当于定义了一个引用

3. android 接入aspjectj

kotlin跟java编译后的路径是不一样的 需要单独处理 这里需要注意下,

String[] kotlinArgs = ["-showWeaveInfo",

"-1.8",

"-inpath", kotlinInPath,

"-aspectpath", aspectpath,

"-d", kotlinPath,

"-classpath", totalPath,

"-bootclasspath", project.android.bootClasspath.join(

File.pathSeparator)]

MessageHandler handler = new MessageHandler(true)

inpath: 需要切面的路径

aspectpath: 切面包的路径 即 @Aspect的路径

-d:  切面后新生成文件路径,一般等于inpath

-classpath: 类库路径, 这里需要注意,需要被切面的包得先加入

具体代码可以看github 最上面的链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值