问题描述
我已经开始为我正在处理的编译器项目使用 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 类),但我似乎无法弄清楚如何生成 main 的主体.谁能给我一个在 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() 中创建一个局部字符串变量,值为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 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();
}
}
这篇关于生成“你好,世界!"带有 Java ASM 库的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!