2011-03-08 50 views
1

我有一個問題。無法實現try/catch /最後變量是最終的

我使用的變量必須是最終的,因爲我在匿名內部類中使用它。

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:我不能用龍目島@Cleanup因爲字段是決賽的匿名內部類工作

回答

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 { 
} 
+0

那麼在這裏你沒有關閉捕獲器中的搜索器?因爲新的IndexSearcher引發CorruptIndex和IOException。那麼,難道不應該關閉嗎? – 2011-03-08 12:59:43

+0

不,我把它關閉在最終的內部,這將永遠執行,只有當新的IndexSearcher成功。如果'new'拋出,搜索器將永遠不會被初始化,也不需要關閉。 – Erik 2011-03-08 13:01:23

+0

謝謝。似乎工作 – 2011-03-08 13:16:17

3

它是醜了一點,但我認爲這會做的伎倆;

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

和替換searcher與所述匿名內部類finalSearcher

+1

不知道如果我喜歡這個黑客:-) – 2011-03-08 13:00:30

+0

你不必像* *它:-) – 2011-03-08 13:12:31

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)); 
    } 
    }); 
}