関流最適化:try-with-resources構文.
1270 ワード
try-with-resourcesはJDK 7の新しい例外処理メカニズムであり、try-catch文ブロックで使用されるリソースを簡単に閉じることができます.–菜鳥教程.
元のシャットダウンフロー:
try-with-resourcesを使用
jdk 1.7例.
出力結果は、test以上のインスタンスではtry文ブロックにリソースbr 1を宣言してから使用する必要があります.Java 9では、リソースbr 1を宣言する必要がなく、同じ結果を得ることができます.jdk 1.9の改良版:
出力結果:test
学習は菜鳥教程から来た.
元のシャットダウンフロー:
try(xxx){ }catch(xxx){ }finally{
xxx.close();
}
try-with-resourcesを使用
try(xxx){
}catch(xxx){ }
jdk 1.7例.
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (BufferedReader br1 = br) {
return br1.readLine();
}
}
}
出力結果は、test以上のインスタンスではtry文ブロックにリソースbr 1を宣言してから使用する必要があります.Java 9では、リソースbr 1を宣言する必要がなく、同じ結果を得ることができます.jdk 1.9の改良版:
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (br) {
return br.readLine();
}
}
}
出力結果:test
学習は菜鳥教程から来た.