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

时间:2011-03-08 12:46:22

标签: 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();
}

问题是我收到编译错误searcher cannot be resolved

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

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

然后我收到编译错误searcher may not be initialized

我该如何解决这个问题?

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

3 个答案:

答案 0 :(得分: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 {
}

答案 1 :(得分:3)

这有点难看,但我认为这样做会有所作为;

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

并在匿名内部类中将searcher替换为finalSearcher

答案 2 :(得分:0)

将try {}块的主体放在另一个方法中:

  IndexSearch searcher = openSearcher();
  try {
    doSearch(searcher, query, resultWorker);
  } finally {
    searcher.close();
  }

private void doSearch(final IndexSearcher searcher, Query query, final ResultWorker resultWorker) {
  searcher.search(new HitCollector() {
    public void collect(int doc, float score) {
      resultWorker.add(new ProcessDocument(searcher.doc(doc));
    }
  });
}