Amir Arad
Amir Arad

Reputation: 6754

java in-memory compilation

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

Upvotes: 10

Views: 6511

Answers (4)

MBCook
MBCook

Reputation: 14504

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.

Upvotes: 6

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147124

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

A quick google pulled up this example usage.

Upvotes: 12

William
William

Reputation: 6428

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.

Upvotes: 0

Draemon
Draemon

Reputation: 34711

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

Upvotes: 4

Related Questions