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

查看:115
本文介绍了是否有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 (ByteCode工程图书馆)这样的java库

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天全站免登陆