1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| public class MyMethodVisitor extends MethodVisitor { public MyMethodVisitor(final MethodVisitor mv) { super(Opcodes.ASM5, mv); }
@Override public void visitCode() { super.visitCode(); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Hello, ASM!"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); } }
public class MyClassVisitor extends ClassVisitor { public MyClassVisitor(final ClassVisitor cv) { super(Opcodes.ASM5, cv); }
@Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions); if (mv != null) { mv = new MyMethodVisitor(mv); } return mv; } }
public class MyPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.android.registerTransform(new Transform() { @Override public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException { transformInvocation.getInputs().forEach(input -> { input.getDirectoryInputs().forEach(directoryInput -> { try { File dest = transformInvocation.getOutputProvider().getContentLocation(directoryInput.getName(), directoryInput.getContentTypes(), directoryInput.getScopes(), Format.DIRECTORY); FileUtils.copyDirectory(directoryInput.getFile(), dest); Files.walkFileTree(directoryInput.getFile().toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".class")) { FileInputStream fis = new FileInputStream(file.toFile()); ClassReader cr = new ClassReader(fis); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS); MyClassVisitor cv = new MyClassVisitor(cw); cr.accept(cv, 0); Files.write(Paths.get(dest.getAbsolutePath(), file.toFile().getAbsolutePath().substring(directoryInput.getFile().getAbsolutePath().length() + 1)), cw.toByteArray()); } return super.visitFile(file, attrs); } }); } catch (IOException e) { e.printStackTrace(); } }); }); }
@Override public String getName() { return "myTransform"; }
@Override public Set<QualifiedContent.ContentType> getInputTypes() { return Collections.singleton(QualifiedContent.DefaultContentType.CLASSES); }
@Override public Set<? super QualifiedContent.Scope> getScopes() { return Collections.singleton(QualifiedContent.Scope.PROJECT); }
@Override public boolean isIncremental() { return false; } }); } }
|