Search code examples
javacompilation

Compile a .class file from a .txt file


I am progamming a game in which the player navigates puzzles by changing the source code of objects within the levels themselves. In order to do this I have a class extending JPanel which is to be written over with the edited source code from the player. My question is how can I compile a class file from a text file, either using java utilities or using beanshell? The text file contains pure java but the player of the game may cause compilation or runtime errors (such as infinite loops) and I want to be able to catch said errors and alert the player.


Solution

  • Sounds like a great idea, but dynamically compiling classes and getting them to execute requires quite a lot of work. There is a library called Janino that (in their own words):

    Janino is a super-small, super-fast Java™ compiler. Not only can it compile a set of source files to a set of class files like JAVAC, but also can it compile a Java™ expression, block, class body or source file in memory, load the bytecode and execute it directly in the same JVM.

    By delegating the work related to actually compiling and running the dynamic code to Janino you can focus on the actual game logic.