1

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.

3
  • Try executing this class in a new process by using ProcessBuilder. Commented May 29, 2015 at 15:53
  • So System.setOut is 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 a PrintStream in the main method and use that instead of System.out? Commented May 29, 2015 at 15:54
  • Since you've already gone through the trouble of creating in memory compilation and custom class loading, I'd say an extra bytecode manipulation step (using for instance ASM) to replace System.out.println(___) with CustomSystem.out(programId).println(___) might be the way to go. Commented May 29, 2015 at 16:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I like the thread-local idea, will try that out later when I have time :)
Will of course become problematic if your "sub programs" spawn threads.
@aioobe - use inheritable thread local? or maybe check call stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.