我正在从事一个项目,该项目要求我随时生成一个 java“.class”文件,稍后可以在 JVM 上编译该文件。在学习和使用同样是基于堆栈的中间编程语言 MSIL (Microsoft IL) 之后,以下是我面临的问题:
- 与 IL(对于 C# 或 VB)相比,“.class”文件中的 java 字节码以结构化方式包含信息,据我所知,它包含程序数据之外的元数据,是是真的??我可以为每个类文件以模板形式生成相同的文件吗??
- 是否必须以二进制形式生成类文件?
我引用了“Joshua Engel 为 Java™ 虚拟机编程”,但它没有达到我的目的,因为我已经了解了 JVm 指令集。
谁能帮我解决这个问题??所有帮助将不胜感激。 生成简单类文件的示例非常有用,因为我还找不到单个 1。
最佳答案
使用 ASM bytecode library 的示例使用 IKVM Java-to-.NET compiler 转换为与 .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);
}
}
}
命令:
$ 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
关于java - 为 JVM 生成 .class 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797996/