Search in sources :

Example 1 with ModifyClassVisiter

use of com.taobao.android.builder.tools.asm.field.ModifyClassVisiter in project atlas by alibaba.

the class AsmTest method test.

@Test
public void test() throws Throwable {
    ClassReader cr = new ClassReader(Config.class.getName());
    ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = new MethodChangeClassAdapter(cw);
    cr.accept(cv, Opcodes.ASM5);
    // Add a new method
    MethodVisitor mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "add", "([Ljava/lang/String;)V", null, null);
    // pushes the 'out' field (of type PrintStream) of the System class
    mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    // pushes the "Hello World!" String constant
    mw.visitLdcInsn("this is add method print!");
    // invokes the 'println' method (defined in the PrintStream class)
    mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
    mw.visitInsn(RETURN);
    // this code uses a maximum of two stack elements and two local
    // variables
    mw.visitMaxs(0, 0);
    mw.visitEnd();
    // Type.getDescriptor(AdviceFlowOuterHolder.class)
    FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "age", Type.INT_TYPE.toString(), null, 1);
    fv.visitEnd();
    FieldVisitor fv2 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "name2", Type.getDescriptor(String.class), null, "name2");
    fv2.visitEnd();
    ModifyClassVisiter cv2 = new ModifyClassVisiter(Opcodes.ASM5);
    cv2.addRemoveField("name");
    cr.accept(cv2, Opcodes.ASM5);
    FieldVisitor fv3 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "name", Type.getDescriptor(String.class), null, "name");
    fv3.visitEnd();
    byte[] code = cw.toByteArray();
    File file = new File("Config.class");
    System.out.println(file.getAbsolutePath());
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(code);
    fos.close();
}
Also used : ModifyClassVisiter(com.taobao.android.builder.tools.asm.field.ModifyClassVisiter) FileOutputStream(java.io.FileOutputStream) ClassReader(org.objectweb.asm.ClassReader) MethodChangeClassAdapter(com.taobao.asm.AsmExample.MethodChangeClassAdapter) ClassVisitor(org.objectweb.asm.ClassVisitor) FieldVisitor(org.objectweb.asm.FieldVisitor) File(java.io.File) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor) Test(org.junit.Test)

Aggregations

ModifyClassVisiter (com.taobao.android.builder.tools.asm.field.ModifyClassVisiter)1 MethodChangeClassAdapter (com.taobao.asm.AsmExample.MethodChangeClassAdapter)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 Test (org.junit.Test)1 ClassReader (org.objectweb.asm.ClassReader)1 ClassVisitor (org.objectweb.asm.ClassVisitor)1 ClassWriter (org.objectweb.asm.ClassWriter)1 FieldVisitor (org.objectweb.asm.FieldVisitor)1 MethodVisitor (org.objectweb.asm.MethodVisitor)1