简体   繁体   English

如何在Java中将变量传递给匿名内部类?

[英]How can I pass a variable to an anonymous inner class in Java?

I have the following method: 我有以下方法:

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

which doesn't compile because the anonymous inner class doesn't have access to the SearchType parameter being passed into the search method. 由于匿名内部类无法访问传递到search方法中的SearchType参数,因此无法编译。

I was wondering how I can get access to this parameter inside the anonymous class? 我想知道如何在匿名类中访问此参数?

The way I have written my class is to duplicate this search method for each SearchType - ie I have three different search methods (with different names) but I wanted to have some code reuse, hence why I am trying to rewrite the method with the SearchType parameter being passed in. 我编写课程的方式是为每个SearchType复制此搜索方法-即,我有三种不同的搜索方法(名称不同),但我想重复使用一些代码,因此为什么要尝试使用SearchType重写该方法传入的参数。

如果将type参数标记为final ,则可以从匿名内部类内部使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM