Direct standard output of dynamically compiled & executed code

46 Views Asked by At

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.

1

There are 1 best solutions below

3
On

Since you are compiling it, you can change the code... replace System.out :)

Or you could set the global System.out to a custom output stream which redirects to different destinations, based on some heuristics. Maybe some thread local flag? etc.