欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

使用asm字节码生成工具生成java类,asm字节码,使用asm字节码生成工具

来源: javaer 分享于  点击 18442 次 点评:60

使用asm字节码生成工具生成java类,asm字节码,使用asm字节码生成工具


使用asm字节码生成工具生成java类:

package byrx.net.gen;import java.io.FileOutputStream;import org.objectweb.asm.ClassWriter;import org.objectweb.asm.MethodVisitor;import static org.objectweb.asm.Opcodes.*;public class HelloClass {    public static void main(String[] args) throws Exception {        ClassWriter cw=new ClassWriter(0);        cw.visit(V1_6, ACC_PUBLIC+ACC_SUPER, "cn/outofmemory//HelloGen", null, "java/lang/Object", null);        //default constructor        {            MethodVisitor mv=cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);            mv.visitCode();            mv.visitVarInsn(ALOAD, 0); //load the first local variable: this            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");            mv.visitInsn(RETURN);            mv.visitMaxs(1,1);            mv.visitEnd();        }        //main method        {            MethodVisitor mv=cw.visitMethod(ACC_PUBLIC+ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);            mv.visitCode();            mv.visitFieldInsn(GETSTATIC,"java/lang/System", "out", "Ljava/io/PrintStream;"); //put System.out to operand stack            mv.visitLdcInsn("Hello"); //load const "Hello" from const_pool, and put onto the operand stack            mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");            mv.visitInsn(RETURN);            mv.visitMaxs(2,1);            mv.visitEnd();        }        cw.visitEnd();        //save bytecode into disk        FileOutputStream out=new FileOutputStream("/tmp/cn/outofmemory/HelloGen.class");        out.write(cw.toByteArray());        out.close();    }}

生成的类如下:

package cn.outofmemory;public class Hello {    public static void main(String[] args) {        System.out.println("Hello");    }}
相关栏目:

用户点评