views:

951

answers:

4

Hi

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

+2  A: 

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

Draemon
Although you didnt technically answered my question, your opened a new possibility for me, that I think WILL prove more usefull in practice (although it will require more learning). my thanks!(+ upvove)
Amir Arad
Perhaps I should have been a bit more explicit that I went through the same thought process myself. I ended up using rhino since it's now part of the JDK. Good luck
Draemon
A: 

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.

William
+8  A: 

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

A quick google pulled up this example usage.

Tom Hawtin - tackline
+4  A: 

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.

MBCook
I've used Janino for a project. It has some limitations but it works well. It is LPGL for what I know...
Mario Ortegón
@Mario Ortegón: Agreed. We used a slightly older version which didn't support any Java 1.5 features which was a pain. They've improved that, although some (like the for (object : collection) syntax) are still missing.
MBCook