Generating a 'Hello, World!' class with the Java ASM library

前端 未结 2 578
萌比男神i
萌比男神i 2020-12-30 09:22

I have started messing around with the ASM API for a compiler project I am working on. However, I am finding that the documentation is less than clear for a newcomer in many

相关标签:
2条回答
  • 2020-12-30 09:26

    If you are using Eclipse, there is a great ASM plugin that will aid your learning. It displays existing Java code as the actual ASM calls needed to instrument said code. It is quite usefully for learning as you can see the ASM calls needed to implement specific Java code.

    0 讨论(0)
  • 2020-12-30 09:50

    You can compile a class using java, then get asm to print out the calls it would take to generate an equivalent class,

    FAQ

    ASMifierClassVisitor

    The ASMifierClassVisitor javadocs actually has the hello world code in it,

    import org.objectweb.asm.*;
    
    public class HelloDump implements Opcodes {
    
      public static byte[] dump() throws Exception {
    
         ClassWriter cw = new ClassWriter(0);
         FieldVisitor fv;
         MethodVisitor mv;
         AnnotationVisitor av0;
    
         cw.visit(49,
                 ACC_PUBLIC + ACC_SUPER,
                 "Hello",
                 null,
                 "java/lang/Object",
                 null);
    
         cw.visitSource("Hello.java", null);
    
         {
             mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
             mv.visitVarInsn(ALOAD, 0);
             mv.visitMethodInsn(INVOKESPECIAL,
                     "java/lang/Object",
                     "<init>",
                     "()V");
             mv.visitInsn(RETURN);
             mv.visitMaxs(1, 1);
             mv.visitEnd();
         }
         {
             mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC,
                     "main",
                     "([Ljava/lang/String;)V",
                     null,
                     null);
             mv.visitFieldInsn(GETSTATIC,
                     "java/lang/System",
                     "out",
                     "Ljava/io/PrintStream;");
             mv.visitLdcInsn("hello");
             mv.visitMethodInsn(INVOKEVIRTUAL,
                     "java/io/PrintStream",
                     "println",
                     "(Ljava/lang/String;)V");
             mv.visitInsn(RETURN);
             mv.visitMaxs(2, 1);
             mv.visitEnd();
         }
         cw.visitEnd();
    
         return cw.toByteArray();
      }
    }
    
    0 讨论(0)
提交回复
热议问题