tags:

views:

60

answers:

2

There's a class I'm working with that has a display() function that prints some information to the screen. I am not allowed to change it. Is there a way to "catch" the string it prints to the screen externally? Edit: it displays to the console.

+5  A: 

The closest thing I can come up with would be to catch and forward everything printed through System.out.

Have a look at the setOut(java.io.PrintStream) method.

A complete example would be:

import java.io.PrintStream;

public class Test {

    public static void display() {
        System.out.println("Displaying!");
    }

    public static void main(String... args) throws Exception {
        final List<String> outputLog = new ArrayList<String>();
        System.setOut(new PrintStream(System.out) {
            public void println(String x) {
                super.println(x);
                outputLog.add(x);
            }

            // to "log" printf calls:
            public PrintStream printf(String format, Object... args) { 
                outputLog.add(String.format(format, args));
                return this;
            }
        });

        display();
    }
}
aioobe
@aioobe How do I do this with `printf(String format,String)` ?
Amir Rachum
Override the method you want to intercept. (just as println is overidden above)
aioobe
@aioobe I meant, how do I get the string after the original `System.out` worked out the format, etc. ?
Amir Rachum
If I understand you correctly, it's not possible.
aioobe
@aioobe I succeeded in doing this with printf just now, but you deserve the accepted answer, so edit this in and I'll accept (sorry, I don't know how to make this code readable in the comment: class Printer extends PrintStream { public List<String> strList; public Printer(OutputStream out) { super(out); this.strList = new LinkedList<String>(); } public PrintStream printf(String format, Object... args) { strList.add(String.format(format, args)); return this; } }
Amir Rachum
+2  A: 

I'm not familiar with a standard display() operation in Java, this might be unique to the framework you're working with. does it print to console? displays a messagebox?

If you are talking about printouts that go through System.out.println() and System.err.println() to the console then yes. You can redirect standard input and standard output. Use:

    System.setErr(debugStream);
    System.setOut(debugStream);

And create the appropriate streams (e.g., files).

Uri