java in-memory compilation

别来无恙 提交于 2019-12-01 03:19:01

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

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

A quick google pulled up this example usage.

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.

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.

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