Background Information:
- I used javax.tools.JavaCompiler to compile code dynamically into memory.
- I used a custom class loader to load and execute the dynamically compiled code.
My Question
let's say someone provides the following code:
package cs.compile;
import java.util.Arrays;
public class Foo {
private static int[] nums = new int[] { 1, 2, 3, 4, 5 };
public static void main(String[] args) {
System.out.println(getWords() + " " + Arrays.toString(nums));
}
public static String getWords() { return "Hello World!!!"; }
}
When I execute main() via reflection, it works fine. But I would like to get the standard-out and standard-error results from the execution and save them in a variable so I can return them as a result.
I'm not sure how to do this as I think, once the class is loaded, that it shares the same standard-out and standard-error as the rest of my application. Is there some standard way of dealing with this perhaps? I don't want to direct my entire application's output streams away, but I'm not sure how to specifically target the new class.
ProcessBuilder.System.setOutis basically too crude for your needs? You want one output stream for each of these programs? And you don't really have control of the source of these programs, you can't accept aPrintStreamin the main method and use that instead ofSystem.out?System.out.println(___)withCustomSystem.out(programId).println(___)might be the way to go.