use of com.taobao.asm.AsmExample.MethodChangeClassAdapter 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();
}
Aggregations