我正在使用构造函数链接,我担心它会导致资源泄漏。这是我的两个构造函数:
/**
* Constructor to build the map based off of a file. Redirects to the Scanner-based constructor
* @param fileName the name of the file to open
*/
public GeoMap(String fileName) throws FileNotFoundException {
this(new Scanner(new File(fileName)));
}
/**
* Constructor to build the map based off of a Scanner. (Probably from an open file.)
* @param scanner the Scanner to read
*/
public GeoMap(Scanner scanner) {
// goes on to read the string data and make an object...
Scanner
从任何类型(键盘、文件等)创建对象很重要,尽管它通常来自文件。问题是我认为这里发生了资源泄漏。每当我阅读文件时,我喜欢在完成后关闭它。问题是,构造函数链接意味着this()
调用必须是第一行。我倾向于做这样的事情:
this(Scanner scannerToClose = new Scanner(new File(fileName)));
在我看来,这会给我一个Scanner
我可以关闭的名字。但这似乎真的让编译器感到困惑——我从中得到了大约 5 个编译时错误,包括许多“找不到符号”问题,这意味着编译器只是没有为这类事情接线。Java 支持这个吗?还是我需要创建一个initFromScanner()
两个构造函数都调用的完全不同的函数?(不优雅。)
谢谢。