「こんにちは、アミーゴ! 今日は、何か新しいことを行う方法、つまり System.out オブジェクトを置き換える方法を学びます。」
System.out は、 Systemクラスで呼び出される静的なPrintStream変数です。この変数には最終修飾子があるため、新しい値を割り当てるだけです。ただし、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!");
}
「なんと興味深いことでしょう。今、これらの小規模クラスが提供する優れた機能を少し理解し始めています。」
「興味深い授業をありがとう、ビラーボ。」
GO TO FULL VERSION