java in-memory compilation

倖福魔咒の 提交于 2019-12-30 08:10:03

问题


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 :)


回答1:


You might find something like rhino or groovy more useful in practice.




回答2:


JDK6 has a Java compiler API. However, it's not necessarily very easy to use.

A quick google pulled up this example usage.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/199241/java-in-memory-compilation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!