如何以编程方式生成 .class 文件?
我想为 Java 的玩具语言编写一个编译器。我想生成可运行的 .class 文件。我想知道可用于执行此操作的最佳库或工具是什么?我知道我可以学习所有指令的二进制格式并构建自己的常量池等,但这似乎是应该已经完成的工作:没有必要重新发明轮子,对吧?
在线搜索我发现了两种不同的Java汇编语言, Jasmin 和 牙买加,但是只有 Jasmin 看起来有些维护。
是否有用于将字节码写入流的 Java 库?这就是 Apache BCEL 吗?
他们的工具是字节码生成的“标准”吗,就像 Antlr 用于解析一样?
PS-玩具语言是 Brainf***,我想要一些可以有简单的“语法”,这样我就可以专注于生成方面而不是解析部分......这将在下一步中进行。
I would like to write a compiler for a toy-language for Java. I would like to generate runnable .class files. I was wondering what is the best library or tool available for doing this? I know I could learn the binary format for all the instructions and build my own constant pool etc, but that seems like work that ought to have been already done: no point reinventing the wheel, right?
Searching online I've found two different Java Assembly languages, Jasmin and Jamaica, however only Jasmin looks somewhat maintained.
Is there a Java library for writing byte codes to a stream? Is this what the Apache BCEL is?
Is their a tool for this that is the "standard" for byte-code generation, like Antlr is for parsing?
PS- The toy language is Brainf***, I wanted something where I could have a simple "grammar" so I could focus on the generation aspect and not the parsing part... that will come later on the next step.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ASM 和 BCEL 基本上做类似的事情。我推荐 ASM,因为它支持更多,更小,并且是最新的 JDK。
ASM and BCEL do basically similar things. I'd recommend ASM as it's much more supported, much smaller, and is up to date JDK-wise.
听起来您正在寻找 Apache BCEL:
It sounds like you're looking for Apache BCEL:
JDK 1.6 具有动态编译 Java 类的能力(请参阅 getSystemJavaCompiler )。这可用于从源代码编译 Java,无需字节码操作或临时文件。我们这样做是为了提高某些反射 API 代码的性能,但它也可以轻松地满足您的目的。
从包含代码的字符串创建 Java 源文件:
然后动态加载新创建的类文件。
或者,使用字节码操作(例如 ASM)动态创建类。
作为另一种选择,有 Scala CAFEBABE 字节码编译库。我个人没有使用过它,但它似乎更适合创建一种新的 JVM 语言。
就解析部分而言,Antlr 应该可以提供服务。
JDK 1.6 has the ability to dynamically compile Java classes (see getSystemJavaCompiler). This can be used to compile Java from source without byte code manipulation or temporary files. We're doing this as a way to improve the performance of some reflection API code, but it will just as easily serve your purpose as well.
Create a Java source file from a string containing the code:
Then you load the newly created class files dynamically.
Alternatively, use byte code manipulation (such as ASM) to create classes on the fly.
As another alternative, there is the Scala CAFEBABE bytecode compilation library. I have not used it personally, but it seems geared more towards creating a new JVM language.
As far as the parsing portion goes, Antlr should serve.
最简单的方法是使用预处理器将玩具语言转换为有效的 .java 源代码,然后使用 javac 对其进行编译。这也是处理的工作方式。
Easiest would be to translate your toy-language into valid .java source code using a preprocessor and then just compile it with javac. That's also the way Processing works.