Java: Compile code at runtime on a jre

644 views Asked by At

I need to compile some code in java while runtime. I looked up this and it looks like the way to do it. So far so good but I need to run the final program on every platform. So I'm getting in troubles if there is a system with a jre only.

Now I thought about getting a compiler as a java lib. But I'm also not sure about the solution of copying the tools.jar from a java jdk into my project. Is it a valid approach or is there another solution or maybe a lib which I can use?

I need this because I want to translate a script into java code and execute it.

Thank you!

-- edit --

Why I need this?

The user should has influence on the behavior of some parts of my program. So there is something like a little script language. Because of performance reasons I think it would the best solution to translate it into java source code and then into bytecode and use it then. This script will not change often and only before the main part of the program runs. If there are better alternatives I would be happy to know about them, too.

If there are any questions or if you need more information about specifics just ask.

1

There are 1 answers

2
Stephen C On BEST ANSWER

The best suggestion I can come up with is Janino: http://docs.codehaus.org/display/JANINO/Home. Unfortunately, the compiler seems to not yet fully support Java 5 (based on what the home page says), so you may have issues to address.


I think your best bet is to bite the bullet and make a JDK a prerequisite. It should not be significantly more difficult to install a JRE than a JDK, and explaining to people that they don't need to do Java development is easy.

There are other alternatives that avoid the problem:

  • Instead of generating Java source code, compile directly to bytecodes. (Not that I would recommend doing this ...)

  • Compile your DSL to an internal form that you can write an interpreter for.


Because of performance reasons I think it would the best solution to translate it into java source code and then into bytecode and use it then.

That sounds like "premature optimization" to me.