This chapter does not appear in the book.
This is the first chapter of a two chapter section on how to convert a Java program into a PNG image which can be compiled and executed like the original source code. This JavaArt project may appear a bit frivolous, but actually illustrates a wide range of useful techniques, including Java 2D graphics generation, dynamic compilation, byte code manipulation, class loaders, reflection, and issues with creating drag-and-drop applications.
A typical JavaArt image is shown in on the right (enlarged by a factor of 4 to make it easier to see).
The image's original Java program is a small drawing application, which can be executed by dropping the PNG file onto a ExecutePixels desktop icon. ExecutePixels dynamically translates the image back into Java, compiles it to byte codes, before passing it to the JVM for execution.
The translation, compilation, and execution are carried out "on-the-fly" without generating any temporary files on the machine (e.g. Java or class files). This approach is often used when executing scripts coded in domain-specific languages: very large speed-ups can be obtained by compiling a script, but it's often not possible to generate temporary files in the process due to space or security restrictions on the device.
This chapter looks at two ways of implementing on-the-fly dynamic compilation. Initially I utilize Java 6's Compiler API, and then try out the Janino compiler API, which focusses on run-time compilation tasks.
One of my Compiler API examples uses Apache Jakarta BCEL (Byte Code Engineering Library) to examine byte code output. I also employ Java class loaders and reflection to load compiled code into the JVM and execute it.
The second JavaArt chapter concentrates on the translation process for converting Java source code into an image (and back again), and some of the ways that the ExecutePixels can be utilized as a desktop icon which reacts automatically to an image being dropped on top of it.
JavaArt was partially inspired by the Piet language, which is based around 'painting' a program using colored blocks. A block may be any shape and have holes of other colors inside it. Program instructions are defined by the color transitions from one block to the next in the image. JavaArt is much more conventional since a programmer writes an ordinary Java program first, then translates it into an image as a separate step.