当在构造函数中打开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”。 –