I have found many references explaining how to programmatically compile a Java class using the JavaCompiler
class:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "a_file_name");
However, I would like to know if there is an open source library that let me compile source code generated programmatically (therefore without a src file being involved) and generate some byte code in an output stream (without generating a class file in the file system).
For example, I am looking for being able to write something like this:
InputStream input = generateSourceCode();
OutputStream output = getByteCode(input);
doCoolStuffWithByteCode(output);
Thanks for any help.
We gave a talk about this use case in JavaOne 2016 (the question is kind of old, but there seems to be some interest still).
There is a repository with examples of practical code generation using javac in-memory.
Specifically look at SimpleJavaCompiler for an example on how to do this in memory that deals with thread safety (we use it in the context of a server) for a single class. It could easily be adapted for a multi-class scenario.
There are also classes to deal with class loading and code generation (scoping of variables, generating unique names, name shadowing, etc.).
To start, look at the JavaCompiler API. Basically:
JavaCompiler
instance.Finally, call the methods the new class.
Here is an example that works with JDK6+:
JavaDocs are your friend:
http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
Look at the last section that refers to the
SimpleJavaFileObject
; it shows you how to use it in conjunction with code that is stored in aString