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 :)
Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM.
Java, being a platform-independent programming language, doesn't work on the one-step compilation. Instead, it involves a two-step execution, first through an OS-independent compiler; and second, in a virtual machine (JVM) which is custom-built for every operating system.
compilation process converts source code into machine code while as execution means that machine code is ready for processing. In general sense compiling means converting source code into executable code. During compilation syntax checking and converting java source code into byte code is done.
Native code compiler for Java translates the Java code into a binary representation that can be linked to precompiled library files and resources to create an executable program. Native code compilers eliminate the need for JVM and interpreters to convert the Java byte code, which is a portable intermediate code.
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 might find something like rhino or groovy more useful in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With