当变量是final时,无法实现try/catch/finally

She*_*ari 1 java lucene compiler-errors

我有个问题.

我使用的变量必须是final,因为我在匿名内部类中使用它.

try { 
    final IndexSearcher searcher = new IndexSearcher(index.getDirectory(),true);

    searcher.search(query, new HitCollector() {
                public void collect(int doc, float score) {
                    try {
                        resultWorker.add(new ProcessDocument(searcher.doc(doc)));
                    } catch (CorruptIndexException e) {
                        log.error("Corrupt index found during search", e);
                    } catch (IOException e) {
                        log.error("Error during search", e);
                    }
                }
            });
} catch (CorruptIndexException e) {
    log.error("Corrupt index found during search", e);
} catch (IOException e) {
    log.error("Error during search", e);
} finally {
    if(searcher != null) 
        searcher.close();
}
Run Code Online (Sandbox Code Playgroud)

问题是我得到编译器错误说 searcher cannot be resolved

如果我像这样移动搜索者:

final IndexSearcher searcher;
try {
    searcher = new IndexSearcher(index.getDirectory(),true);
Run Code Online (Sandbox Code Playgroud)

然后我得到编译错误说searcher may not be initialized.

我怎样才能解决这个问题?

PS:我不能使用Lombok @Cleanup,因为该字段必须是匿名内部类才能工作的最终字段

Eri*_*rik 5

try { 
    // if new IndexSearcher throws, searcher will not be initialized, and doesn't need a close. The catch below takes care of reporting the error.
    final IndexSearcher searcher = new IndexSearcher(index.getDirectory(),true);
    try {
        searcher.search(query, new HitCollector() {
                public void collect(int doc, float score) {
                    try {
                        resultWorker.add(new ProcessDocument(searcher.doc(doc)));
                    } catch (CorruptIndexException e) {
                        log.error("Corrupt index found during search", e);
                    } catch (IOException e) {
                        log.error("Error during search", e);
                    }
                }
            });
    } finally {
        searcher.close();
    }
} catch (CorruptIndexException e) {
    log.error("Corrupt index found during search", e);
} catch (IOException e) {
    log.error("Error during search", e);
} finally {
}
Run Code Online (Sandbox Code Playgroud)