有什么办法可以避免此代码中的return null

@Test
public void testFrontEndPing() throws Exception {
    String url = frontEndUrl("ping");
    HttpGet httpGet = new HttpGet(url);
    httpClient.execute(httpGet, httpResponse -> {
            assertEquals(200, httpResponse.getStatusLine().getStatusCode());
            return null;
        }
    );
}

最佳答案

您可以编写一个包装方法,如下所示:

static void execute(HttpClient client, HttpUriRequest request,
                    Consumer<HttpResponse> handler) {
    client.<Void>execute(request, response -> {
        handler.accept(response);
        return null;
    });
}


并像这样使用它:

execute(httpClient, httpGet, httpResponse ->
    assertEquals(200, httpResponse.getStatusLine().getStatusCode()));

关于java - 在Java Lambda中避免不必要的返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32316262/

10-10 11:22