"สวัสดี Amigo! วันนี้คุณจะได้เรียนรู้วิธีการทำสิ่งใหม่: แทนที่วัตถุ System.out"
System.outเป็นตัวแปรPrintStream แบบสแตติกที่ถูกเรียก ใช้ในคลาสSystem ตัวแปรนี้มี ตัวแก้ไข ขั้นสุดท้ายดังนั้นคุณเพียงแค่กำหนดค่าใหม่ให้กับมัน อย่างไรก็ตาม คลาส System มีวิธีการพิเศษในการทำเช่นนี้: setOut(PrintStream stream ) และนั่นคือสิ่งที่เราจะใช้

"น่าสนใจ แล้วเราจะแทนที่ด้วยอะไรดีล่ะ"

"เราต้องการวัตถุบางอย่างที่สามารถรวบรวมข้อมูลเอาต์พุตได้ByteArrayOutputStreamเหมาะที่สุดสำหรับงานนี้ นี่คือคลาสพิเศษที่เป็นอาร์เรย์แบบไดนามิก (ปรับขนาดได้) และใช้อินเทอร์เฟซ OutputStream"

"อะแดปเตอร์ระหว่างอาร์เรย์และ OutputStream"

"อะไรประมาณนั้น นี่คือลักษณะของรหัสของเรา"

รหัส
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!");
}

“แล้วเราจะทำอย่างไรกับแถวนี้”

"เอาล่ะ อะไรก็ได้ที่เราต้องการ ตัวอย่างเช่น เราจะย้อนกลับ จากนั้นโค้ดจะมีลักษณะดังนี้:"

รหัส
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!");
}

"น่าสนใจจัง! ตอนนี้ฉันเริ่มเข้าใจความสามารถอันยอดเยี่ยมของชั้นเรียนขนาดเล็กเหล่านี้แล้ว"
"ขอบคุณสำหรับบทเรียนที่น่าสนใจ บิลาโบ"