生成'Hello,World!'使用Java ASM库的类 [英] Generating a 'Hello, World!' class with the Java ASM library

查看:378
本文介绍了生成'Hello,World!'使用Java ASM库的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始乱用我正在处理的编译器项目的ASM API。但是,我发现文档对于很多地方的新手来说还不太清楚,我认为有一个很好的例子来生成一个只打印Hello,World!的类。这将是一个很好的例子。

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 places and I thought having a good solid example of generating a class that simply prints "Hello, World!" would be a great example to have on here.

目前,我可以生成一个带有main()的类(使用ClassWriter,ClassVisitor和MethodVisitor类)但我可以似乎弄清楚如何生成主体。任何人都可以给我一个在ASM中生成类文件的示例:

Currently, I can generate a class with a main() (using the ClassWriter, ClassVisitor and MethodVisitor classes) but I can't seem to work out how to generate main's body. Could anyone give me an example of generating a class file in ASM that:


  • 包含一个main()

  • 在main()中创建一个本地String变量,其值为Hello,World!。

  • 打印变量

推荐答案

您可以使用java编译一个类,然后使用asm打印出生成等效类所需的调用,

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

常见问题解答

ASMifierClassVisitor

ASMifierClassVisitor javadocs实际上包含hello world代码,

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();
  }
}

这篇关于生成'Hello,World!'使用Java ASM库的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆