Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret something, and run the generated bytecode in Java?

I'm writing a toy interpreter with a REPL in Java. I'd like to generate bytecode from the language and run that, instead of interpreting an AST and running that instead.

Since my Java is a bit rusty, is it possible to run generated bytecode on the fly on the JVM?

like image 721
jumoel Avatar asked Jun 25 '09 19:06

jumoel


2 Answers

You can use java.lang.Classloader.defineClass(), which turns bytecode into a Class object. You can the call newInstance() on the resulting Class object, and off you go.

like image 157
skaffman Avatar answered Oct 21 '22 23:10

skaffman


Have a look at Javassist which contains a snippet compiler allowing you to compile Java snippets to bytecode and define them as a method in a class which you can then invoke.

like image 43
Thorbjørn Ravn Andersen Avatar answered Oct 22 '22 00:10

Thorbjørn Ravn Andersen