简体   繁体   English

如何使方法返回类型为 Callable<boolean></boolean>

[英]How to make a method return type as Callable<Boolean>

In one of my methods:在我的一种方法中:

public void pageIsReady()

the implementation is实施是

Awaitility.await().atMost(5, TimeUnit.SECONDS).until(isPageLoaded());

Here, isPageLoaded() method returns boolean value, but I want it to return a Callable of Boolean, because the until() method in Awaitility expects Callable<Boolean> .在这里, isPageLoaded()方法返回 boolean 值,但我希望它返回 Boolean 的Callable ,因为Awaitility中的until()方法需要Callable<Boolean>

Please help me to make the method isPageLoaded() return Callable<Boolean>请帮助我使方法isPageLoaded()返回Callable<Boolean>

Here is the implementation of isPageLoaded() method:下面是isPageLoaded()方法的实现:

protected Boolean isPageLoaded() {
    String jsQuery = "function pageLoaded() "
            + "{var loadingStatus=(document.readyState=='complete');"
            + "return loadingStatus;};"
            + "return pageLoaded()";

    boolean isSuccess = false;
    try {
        isSuccess = (Boolean) evaluateJavascript(jsQuery);
    } catch (Exception exp) {
        exp.printStackTrace();
    }
    return isSuccess;
}

Just define your isPageLoaded() method as follows:只需按如下方式定义您的isPageLoaded()方法:

protected Callable<Boolean> isPageLoaded() {
    //code..
}

The easiest way to do that is to use a method reference Callable<Boolean> isPageLoaded = this::isPageLoaded , or to use it explicitly as lambda Callable<Boolean> isPageLoaded = () -> isPageLoaded();最简单的方法是使用方法引用Callable<Boolean> isPageLoaded = this::isPageLoaded ,或者将其显式用作 lambda Callable<Boolean> isPageLoaded = () -> isPageLoaded();

This would look like这看起来像

Awaitility.await().atMost(5, TimeUnit.SECONDS).until(this::isPageLoaded);
Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> isPageLoaded());

Another way would be to define your method as returning a Callable<Boolean> and then using lambda syntax () -> {} to write the callable.另一种方法是将您的方法定义为返回Callable<Boolean>然后使用 lambda 语法() -> {}来编写可调用对象。

protected Callable<Boolean> isPageLoaded() {
    return () -> {
        String jsQuery = "function pageLoaded() "
            + "{var loadingStatus=(document.readyState=='complete');"
            + "return loadingStatus;};"
            + "return pageLoaded()";

        boolean isSuccess = false;
        try {
            isSuccess = (Boolean) evaluateJavascript(jsQuery);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return isSuccess;
    };
}

Lambda expressions and method references can be quite powerful tools. Lambda 表达式和方法引用是非常强大的工具。

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

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