in Java I am redirecting System.out to a ByteArrayOutputStream but it is not working - why?

65 Views Asked by At

I have the following class:

class Bla {
   private static final Consumer<String> OUTPUT = System.out::println;

   public void print() {
      printStuff(OUTPUT);
   }

   public void printStuff(Consumer<String> consumer) {
      consumer.accept("Bla");

   }
}

Test code:

Bla bla = new Bla();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream standardOut = System.out;
System.setOut(new PrintStream(baos));
bla.print();
LOG.info(baos.toString().trim()); <-- This does not work
System.setOut(standardOut);

It logs nothing. Why? When I inline OUTPUT, then it works.

1

There are 1 best solutions below

0
jtahlborn On

The problem is that when the Bla class initializes, it takes a reference to System.out at that point in time. When you reset System.out in the subsequent code, it has no affect on the value of Bla.OUTPUT.

I think this will do what you want:

OUTPUT = s -> System.out.println(s);

because it will always use the current value of System.out.