为JVM生成.class文件

Rag*_*ali 5 java bytecode jvm-languages

我正在开发一个项目,要求我随时生成一个java".class"文件,以后可以在JVM上编译.在学习并使用MSIL(Microsoft IL)(也是基于堆栈的中间编程语言)之后,我面临的问题如下:

  1. 与IL(对于C#或VB)相比,".class"文件中的java字节码以结构化方式包含信息,据我所知,它包含除程序数据之外的元数据,是真的吗? ?我可以为每个类文件在模板表单中生成相同的文件吗?
  2. 是否必须以二进制生成类文件?

我已经提到"由Joshua Engel编写Java™虚拟机程序",但由于我已经了解了JVm指令集,因此它没有达到我的目的.

任何人都可以帮我这个吗?所有帮助将受到高度赞赏.生成简单类文件的示例将非常有用,因为我还无法找到单个1.

Sto*_*bor 4

使用IKVM Java-to-.NET 编译器将ASM 字节码库转换为与 .NET 一起使用的示例:

你好.cs:

using System;
using System.IO;
using org.objectweb.asm;

namespace test.helloWorld
{
    public class helloDump
    {

        public static byte[] dump ()
        {

            ClassWriter cw = new ClassWriter(0);
            MethodVisitor mv;

            cw.visit(Opcodes.__Fields.V1_6, Opcodes.__Fields.ACC_PUBLIC + Opcodes.__Fields.ACC_SUPER, "hello", null, "java/lang/Object", null);

            mv = cw.visitMethod(Opcodes.__Fields.ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.__Fields.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.__Fields.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
            mv.visitInsn(Opcodes.__Fields.RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();

            mv = cw.visitMethod(Opcodes.__Fields.ACC_PUBLIC + Opcodes.__Fields.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
            mv.visitCode();
            mv.visitFieldInsn(Opcodes.__Fields.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
            mv.visitLdcInsn("Hello World!");
            mv.visitMethodInsn(Opcodes.__Fields.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
            mv.visitInsn(Opcodes.__Fields.RETURN);
            mv.visitMaxs(2, 1);
            mv.visitEnd();

            cw.visitEnd();

            return cw.toByteArray();
        }

        public static void Main(string[] args)
        {
            FileStream helloWorldFile = new FileStream("hello.class", FileMode.Create);
            byte[] helloWorldClass = dump();
            helloWorldFile.Seek(0, SeekOrigin.Begin);
            helloWorldFile.Write(helloWorldClass, 0, helloWorldClass.Length);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

命令:

$ ikvmc -out:org.objectweb.asm.dll -target:library -version:3.2.0.0 asm-3.2.jar
$ mcs -r:org.objectweb.asm.dll  hello.cs
$ mono hello.exe
$ ls hello.class
$ java hello
Run Code Online (Sandbox Code Playgroud)