是否有 Java 库可以从 AST 生成类文件? [英] Is there a Java library to generate class files from an AST?

查看:26
本文介绍了是否有 Java 库可以从 AST 生成类文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本页 描述了我如何使用 javac 中的代码生成器来生成给定的代码我可以构建一个 AST(使用我编写的单独的解析器).该技术涉及编辑 javac 的源代码以基本上绕过 Java 解析器,以便可以将他/她自己的 AST 提供给代码生成器.这可以工作,但我希望以更简洁的方式来完成.我想将 javac 的代码生成部分作为库包含在我的项目中,这样我就可以使用它来生成代码,而无需附带 javac 的其余源代码.

This page describes how I can use the code generator in javac to generate code given that I can build an AST (using a separate parser which I wrote). The technique involves editing javac's source code to basically bypass the Java parser, so that one could supply his/her own AST to the code generator. This could work, but I was hoping to do it in a slightly cleaner way. I want to include the code generating part of javac as a library in my project so I can use it to generate code, without bringing with it the rest of javac's source.

有没有办法用 javac 做到这一点,或者有没有更好的库?

Is there a way to do this with javac, or is there perhaps a better library?

另外,请随意更改问题的标题.我想不出更好的方法,但它有点模棱两可.如果你建议修改一个更好的标题,我会接受.

Also, feel free to change the question's title. I couldn't think of a better one, but it's a little ambiguous. If you suggest an edit for a better title, I'll accept it.

推荐答案

我想你可能感兴趣的是像 BCEL(字节码工程库)

I think what you might be interested in is a java library like BCEL(ByteCode Engineering Library)

当我学习编译器构造的课程时,我玩过它,基本上,它有一个很好的包装器来生成常量池,将命名的字节码指令插入到方法中等等,然后当你完成后,你可以使用自定义类加载器在运行时加载类,或以正常方式将其写入文件.

I played around with it back when I took a class on compiler construction, basically, it has a nice wrapper for generating the constant pool, inserting named bytecode instructions into a method and whatnot, then when you are done, you can either load the class at runtime with a custom classloader, or write it out to a file in the normal way.

使用 BCEL,从语法树到 Java 字节码应该相对容易,虽然有点乏味,但在某些情况下,您可能只想使用 BCEL 生成原始字节码而不构建树.

With BCEL, it should be relatively easy to go from the syntax tree to the java bytecodes, albeit a bit tedious, but you may want to just use BCEL to generate the raw bytecode without building the tree as well in some cases.

这篇关于是否有 Java 库可以从 AST 生成类文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆