[英]How can I pass a variable to an anonymous inner class in Java?
我有以下方法:
public Promise<List<SearchResult>> search(String searchTerms, SearchType type) {
Promise<List<SearchResult>> response = WS.url(type.url + searchTerms).
get().map(
new Function<WSResponse, List<SearchResult>>() {
public List<SearchResult> apply(WSResponse response) {
Document doc = Jsoup.parse(response.getBody());
Elements results = doc.select(type.selector);
return buildResultList(results);
}
}
);
return response;
}
由於匿名內部類無法訪問傳遞到search
方法中的SearchType
參數,因此無法編譯。
我想知道如何在匿名類中訪問此參數?
我編寫課程的方式是為每個SearchType
復制此搜索方法-即,我有三種不同的搜索方法(名稱不同),但我想重復使用一些代碼,因此為什么要嘗試使用SearchType
重寫該方法傳入的參數。
如果將type
參數標記為final
,則可以從匿名內部類內部使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.