调用超级构造函数时试用资源
2022-09-02 03:54:58
在构造函数中打开一个,然后将其传递给超级构造函数时,有什么好方法可以使用 try-with-resources 吗?InputStream
基本上我想做的是这样的:
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