Teo Teo - 5 months ago 25
Java Question

Compile code fully in memory with javax.tools.JavaCompiler

I'm using the JavaCompiler from the javax.tools package (JDK 1.7) to compile some stuff on the fly, like this:

compiler.run(null, null, "-cp", paths, "path/to/my/file.java");


It works but I would like to do it all in memory (e.g. pass a string with the code, not the source file, and get the byte code back not a .class file). I found that extending the
InputStream
and
OutputStream
parameters is no use since it's probably just the same as in the console. Do you know a way to make the run method work like this? Or do you know a confirmed way to do this with the
getTask()
method? (extending the FileManager looks easy but isn't that easy :)

Answer

I've run the above code in Mac OS Java 7. None of them works. So i wrote one https://github.com/trung/InMemoryJavaCompiler

StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append("   public String hello() { return \"hello\"; }");
sourceCode.append("}");

Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", sourceCode.toString());