简体   繁体   中英

how to pass function to method parameter in java

APIResponse res = kpiAPIObject.getALLKPIDefinition(); --> function a

Boolean status = res.getNodeValues("shortName").contains(kpiName); --> function b

public void dynamicWait(function a,function b)
{
    long t = System.currentTimeMillis();
    while (t > System.currentTimeMillis() - 180000 ) {
        res = /* execute function a here */
        if(/* execute function b here */) {
            break;
        } else {
            Thread.sleep(30000);
            continue;
        }
    }  
}

Thanks in advance

Sounds like you could use some lambdas:

Supplier<APIResponse> a = kpiAPIObject::getALLKPIDefinition;
Predicate<APIResponse> b = res -> res.getNodeValues("shortName").contains(kpiName);

Then call them like:

APIResponse res = a.get();
if (b.test(res)) {
    break;
}

In Java, there are various ways. If you take a look at java.util.function package, you can see

  • Function: Takes one argument, produces one result
  • Consumer: Takes one argument, produces nothing.
  • BiConsumer: Takes two arguments, produces nothing.
  • Supplier: Takes no argument, produces one result.
  • Predicate: Boolean value function of one argument

You can used them as inputs for your method and execute it within.

In you case, you will use Supplier for function a and Predicate for function b.

Supplier<APIResponse> a = () -> { return kpiAPIObject.getALLKPIDefinition(); }; Predicate<APIResponse> b = res -> res.getNodeValues("shortName").contains(kpiName);

public void dynamicWait(Supplier<APIResponse> a,Predicate<APIResponse> b)

{

long t = System.currentTimeMillis();

while (t > System.currentTimeMillis() - 180000 ){

            res = a.get();
            if(b.test(res)){
                break;
            }
            else{
                Thread.sleep(30000);
                continue;
            }
        }  

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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