How to add a CodeBlock as part of MethodSpec's statement in Javapoet

669 Views Asked by At

I want to create a lambda expression like:

// some code
CompletableFuture.handle((s,t) -> {
if(t != null){
//some code}
else{
// some code}
});
//some code

I have all logic of if-else in a CodeBlock code, and parent code in the MethodSpec method.

I am trying to add this code as follows:

method.addStament("CompletableFuture.handle((s,t) -> $N)", code.build);

which obviously is not working! Want help only for Lamda part.

Any help !

1

There are 1 best solutions below

0
ttdevs On

I try this:

 /**
 * Out code is below:
 * 
 * public void lambdaTest() {
 *   CompletableFuture.supplyAsync(() -> 1).handle((num, throwable) ->  {
 *     if (num > 2) {
 *       return true;
 *     }
 *     return false;
 *   } );
 * }
 * @return
 */
public MethodSpec lambdaTest() {
    String param1 = "num", param2 = "throwable";
    CodeBlock.Builder builder = CodeBlock.builder();
    CodeBlock.Builder subBuilder = CodeBlock.builder();
    subBuilder.beginControlFlow("if ($N > 2)", param1)
            .addStatement("return true")
            .endControlFlow()
            .addStatement("return false");
    builder.beginControlFlow("CompletableFuture.supplyAsync(() -> 1).handle(($N, $N) -> ", param1, param2)
            .add(subBuilder.build())
            .endControlFlow(")");
    return MethodSpec
            .methodBuilder("lambdaTest")
            .addModifiers(Modifier.PUBLIC)
            .returns(void.class)
            .addCode(builder.build())
            .build();
}