java内存中编译
如何在运行时从字符串生成字节码(Byte[]),而不使用“javac”进程或类似的东西? 有没有一种简单的方法来调用编译器?
后来补充:
我选择接受实际上最适合我 情况。 我的应用程序是一个业余爱好项目,仍处于设计草图阶段,现在是考虑插入新技术的最佳时机。 另外,由于应该帮助我进行 BL 的人是一名 JavaScript 开发人员,因此在这种情况下使用 JavaScript 解释器而不是存根编译器+类加载器的想法似乎对我更有吸引力。 这个问题的其他(未接受的)答案内容丰富,据我所知,很好地回答了我的问题,所以谢谢,但我会尝试 犀牛 :)
How can i generate bytecode (Byte[]) from a String at runtime, without using a "javac" process or something of this sort? is there a simple way of calling the compiler like that?
later addition:
I chose to accept the solution that actually best fits my situation. my application is a hobby-project still in design sketch phase, and it is the right time to consider inserting new technology. also, since the guy that's supposed to help me with BL is a JavaScript developer, the idea of using a JavaScript interpreter instead of a stub compiler+classLoader seems more appealing to me in this situation. other (unaccepted) answers of this question are informative and, as far as i can tell, answer my question very well, so thanks, but I'm going to try Rhino :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
JDK6 有一个 Java 编译器 API。 然而,它并不一定很容易使用。
谷歌很快就找到了这个示例用法。
JDK6 has a Java compiler API. However, it's not necessarily very easy to use.
A quick google pulled up this example usage.
我认为你最好的选择是 Janino。 这将允许您在运行时编译代码并从程序的其余部分调用它。 我们在一些系统中使用它来动态更新一些类。
它不是免费的。 它工作得很好,但是每次加载新类(或类的版本)时它都会使用永久生成空间,因此如果您有一个(真正)长时间运行的进程(或加载大量新类的进程),最终您将耗尽内存)但是如果这是一个问题,您可以更改 JVM 中的永久生成空间量,以将该屏障移出相当远的距离。
Janino 实际上是一个编译器,但如果您需要在该级别进行操作,您可以看到它如何注入字节码。 您最终可能需要按照 Tom Hawtin 的建议创建一个类加载器或使用 Java 编译器 API。
I think your best shot is going to be Janino. That will let you compile code at runtime and call it from the rest of your program. We use it in some of our systems to let us dynamically update some classes.
It's not free. It works well, but it uses permgen space every time you load a new class (or version of a class) so you will run out of memory eventually if you have a (really) long running process (or something that loads lots of new classes) but you can change the amount of permgen space in the JVM to move that barrier out quite a way if that's a problem.
Janino is actually a compiler, but you could see how it injects the bytecode if you need to operate at that level. You may need to end up making a classloader or use the Java compiler API as Tom Hawtin suggested.
您可能会发现像 rhino 或 groovy 这样的东西在实践中更有用。
You might find something like rhino or groovy more useful in practice.
只要 JDK 中的 tools.jar 文件位于类路径中,您就可以访问编译器。 它的文档位于此处。 该 API 并不像某些解释语言中的
eval()
那么简单,但它确实存在。您可能还需要进入一些奇怪的类加载器代码才能实际运行该代码,我对此并不完全确定。
You can access the compiler as long as the tools.jar file from your JDK is on the classpath. The documentation for it is here. The API isn't as simple as
eval()
in some interpreted languages but it is there.You might also have to get into some weird ClassLoader code to actually run that code, I'm not totally sure about that.