package com.gradle.ares import com.gradle.JarZipUtil import com.gradle.ModifyClassTransform import org.gradle.api.Project import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassWriter /** * Created by Glen on 2017/2/7. */ public class AresTransform extends ModifyClassTransform { public AresTransform(Project project) { super(project); } @Override protected void handleChangedFile(File input) { String path = input.absolutePath.replace("/", "\\") if (input.isFile()) { debug("changed:" + path) if (path.endsWith(".class")) { modifyClass(input) } else if (path.endsWith(".jar")) { boolean modify = false if (path.contains("exploded-aar") && !path.contains("exploded-aar\\com.android.support")) { modify = true } if (modify) { //需要处理的jar包 File tmp = new File(input.getParent() + File.separator + "tmp") tmp.deleteOnExit() JarZipUtil.unzipJar(input, tmp.absolutePath) modify = false tmp.eachFileRecurse { File file -> if (file.isFile()) { if (modifyClass(file)) { modify = true } } } if (modify) JarZipUtil.zipJar(tmp.absolutePath, input) } } } } /** * 修改类文件 * @param clazz * @return */ private boolean modifyClass(File clazz) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS) ClassReader cr = new ClassReader(clazz.bytes) ClassAdapter adapter = new ClassAdapter(cw, project) cr.accept(adapter, ClassReader.SKIP_DEBUG) if (adapter.modify) { FileOutputStream out = new FileOutputStream(clazz) out.write(cw.toByteArray()) out.close() } return adapter.modify } }