- 写一个Plugin
- 创建一个配置类
- 通过Transfrom Api 注入配置
- 扫描包名通过ASM注入到class中
- gradle插件的方法请自行查阅百度;
- 创建一个dsl,传入要插入的方法的信息,注入Transform
project.extensions.create(EXT_NAME,AutoRegisterConfig)//写入自定义配置,创建dsl
def android = project.extensions.getByType(AppExtension);
def transformImpl = new RegeisterTransform();
android.registerTransform(transformImpl);
复制代码
- 遍历directoryInputs,找到要注入的类,插入asm
ClassReader cr = new ClassReader(bytes);
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv = new MyClassVisitor(Opcodes.ASM5, cw);
cr.accept(cv, ClassReader.EXPAND_FRAMES);
byte[] b = cw.toByteArray();
复制代码
- 采用AdpterAdvice注入到方法,这是MethodVistor的子类,封装的接口可以方便插入代码到方法内部,在onMethodEnter中写入方法,ig:
mv.visitMethodInsn(INVOKESTATIC, "com/xxx/myapplication/TimeLog","printTime", "()V");
参数可以通过第一步创建的dsl获取到 第一个参数代表Static,第二个参数是全类名,第三方参数是方法名,第四个参数是返回值类型(百度自行查阅字节码的类型表示) 插入的方法:
public class TimeLog {
public static void printTime(){
Log.e("time",System.currentTimeMillis() + "");
}
}
复制代码
- 将生成的byte[] 重新写回源文件
FileOutputStream fos = new FileOutputStream(file.absolutePath);
fos.write(b);
fos.close();
复制代码
- 依赖插件,build项目运行