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.
The problem is that when the
Blaclass initializes, it takes a reference toSystem.outat that point in time. When you resetSystem.outin the subsequent code, it has no affect on the value ofBla.OUTPUT.I think this will do what you want:
because it will always use the current value of
System.out.