當在構造函數中打開InputStream
,然後將其傳遞給超級構造函數時,是否有任何使用try-with-resources的好方法?嘗試與資源時調用超級構造函數
基本上就是我想要做的是這樣的:
public class A {
public A(InputStream stream) {
// Do something with the stream but don't close it since we didn't open it
}
}
public class B {
public B(File file) {
// We open the stream so we need to ensure it's properly closed
try (FileInputStream stream = new FileInputStream(file)) {
super(new FileInputStream(file));
}
}
}
但是,當然,因爲super
必須在構造函數中的第一條語句,這是不允許的。有沒有什麼好的方法來實現這一目標?
我希望調用者提供輸入流給'public B(InputStream in)'並關閉它。沒有理由讓派生類比基類更少用途。 – EJP
功能更多,但使用起來也更麻煩。我可以支持這兩種,但不具有'B(文件文件)'構造函數不是一個選項。 – Raniz
在我看來,你的問題來自消耗A的構造函數內的流。如果不是這種情況,您只需將該流存儲在一個實例變量中並設置「AutoClosable」。 –