Reputation: 43
I am writing java program that creates different instances of Runnable objects given by someone and then runs them. For instance user gives me a .class file with runnable class and I create instance of that object and run it. Everything works fine until I decided to monitor every different thread's progress. Lets say that current Runnable object print all the numbers from 1 to 9 in console. I want to catch that output and return it as a String. Using System.setOut(..)
prevents me from using console, so it is not an option.
Upvotes: 3
Views: 98
Reputation: 533790
Using setOut
doesn't prevent you from using the console, if you save it first and it is your only option unless you use byte code instrumentation.
static final PrintStream OUT = System.out;
static {
// capture all System.out
System.setOut(new MyPrintStream());
OUT.println("Print as normal");
}
class MyPrintStream extends PrintStream {
final ThreadLocal<StringBuilder> text = ThreadLocal.withInitial(() _> new StringBuilder());
public void print(String s) {
StringBuilder sb = text.get();
sb.append(s);
}
public void println(String s) {
StringBuilder sb = text.get();
sb.append(s).append('\n');
// do something with sb.
}
Upvotes: 3