So I recently learned of the new JavaCompiler API available in JDK 1.6. This makes it very simple to compile a String to a .class file directly from running code:
String className = "Foo";
String sourceCode = "...";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<JavaSourceFromString> unitsToCompile = new ArrayList<JavaSourceFromString>()
{{
add(new JavaSourceFromString(className, sourceCode));
}};
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, unitsToCompile).call();
fileManager.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(className + ".class");
IOUtils.copyStream(fis, bos);
return bos.toByteArray();
You can grab the source to JavaSourceFromString from the Javadoc.
This will very handily compile sourceCode to Foo.class in the current working directory.
My question is: is it possible to compile straight to a byte[] array, and avoid the messiness of dealing with File I/O altogether?
Maybe you could create your own
javax.tools.JavaFileManagerimplementing class where you would return your own implementation ofjavax.tools.FileObjectwhich would then write it out to memory instead to disk. So for your subclass ofjavax.tools.FileObjectWriter openWriter() throws IOExceptionmethod you would return ajava.io.StringWriter. All the methods should be converted to theirStringcounterparts.