"Hallo, Amigo! Vandaag ga je leren hoe je iets nieuws kunt doen: het System.out-object vervangen."
System.out is een statische PrintStream- variabele die wordt aangeroepen in de klasse System . Deze variabele heeft de laatste modifier, dus u wijst er eenvoudig een nieuwe waarde aan toe. De klasse System heeft hiervoor echter een speciale methode: setOut(PrintStream stream) . En dat is wat we zullen gebruiken.

"Interessant. En waarmee gaan we het vervangen?"

"We hebben een object nodig dat de uitvoergegevens kan verzamelen. ByteArrayOutputStream is het meest geschikt voor deze taak. Dit is een speciale klasse die een dynamische (aanpasbare) array is en de OutputStream-interface implementeert."

"Een adapter tussen een array en OutputStream?"

"Zoiets. Zo ziet onze code eruit."

Code
public static void main(String[] args) throws Exception
{
 //Save the current PrintStream in a special variable
 PrintStream consoleStream = System.out;

 //Create a dynamic array
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 //Create an adapter for the PrintStream class
 PrintStream stream = new PrintStream(outputStream);
 //Set it as the current System.out
 System.setOut(stream);

 //Call a function that knows nothing about our changes
 printSomething();

 //Convert the data written to our ByteArray into a string
 String result = outputStream.toString();

 //Put everything back to the way it was
 System.setOut(consoleStream);
}

public static void printSomething()
{
 System.out.println("Hi");
 System.out.println("My name is Amigo");
 System.out.println("Bye-bye!");
}

"En wat gaan we doen met deze regel?"

"Nou, wat we maar willen. We zouden het bijvoorbeeld omdraaien. Dan zou de code er zo uitzien:"

Code
public static void main(String[] args) throws Exception
{
 //Save the current PrintStream in a special variable
 PrintStream consoleStream = System.out;

 //Create a dynamic array
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 //Create an adapter for the PrintStream class
 PrintStream stream = new PrintStream(outputStream);
 //Set it as the current System.out
 System.setOut(stream);

 //Call a function that knows nothing about our changes
 printSomething();

 //Convert the data written to our ByteArray into a string
 String result = outputStream.toString();

 //Put everything back to the way it was
 System.setOut(consoleStream);

 //Reverse the string
 StringBuilder stringBuilder = new StringBuilder(result);
 stringBuilder.reverse();
 String reverseString = stringBuilder.toString();

 //Output it to the console
 System.out.println(reverseString);
}

public static void printSomething()
{
 System.out.println("Hi");
 System.out.println("My name is Amigo");
 System.out.println("Bye-bye!");
}

"Wat interessant! Nu begin ik een klein beetje te begrijpen van de geweldige mogelijkheden die deze kleine klassen bieden."
"Bedankt voor de interessante les, Bilaabo."