Thursday, 22 July 2021

Javapoet: CodeBlock: Relative arguments

Pass an argument value for each placeholder in the format string to CodeBlock.add().

 

Example

Builder codeBlock1 = CodeBlock.builder().add("Hi, my name is '$L' and I am '$L' years old", "Krishna", 32);

Above snippet generates the snippet ‘Hi, my name is 'Krishna' and I am '32' years old’.

 

Find the below working application.

 

CodeBlockRelativeArgumentsDemo.java

package com.sample.app;

import java.io.IOException;

import javax.lang.model.element.Modifier;

import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.CodeBlock.Builder;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

public class CodeBlockRelativeArgumentsDemo {

  public static void main(String args[]) throws IOException {

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("main");
    methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.STATIC);
    methodBuilder.returns(void.class);
    methodBuilder.addParameter(String[].class, "args");

    Builder codeBlock1 = CodeBlock.builder().add("Hi, my name is '$L' and I am '$L' years old", "Krishna", 32);
    
    methodBuilder.addStatement("$T.out.println($S)", System.class, codeBlock1.build().toString());
    MethodSpec mainMethod = methodBuilder.build();

    String className = "Test";
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className);
    classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    classBuilder.addMethod(mainMethod);
    TypeSpec helloWorldTypeSpec = classBuilder.build();

    String packageName = "com.sample.app";
    JavaFile javaFile = JavaFile.builder(packageName, helloWorldTypeSpec).build();

    javaFile.writeTo(System.out);
  }

}


Generated code

package com.sample.app;

import java.lang.String;
import java.lang.System;

public final class Test {
  public static void main(String[] args) {
    System.out.println("Hi, my name is 'Krishna' and I am '32' years old");
  }
}


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment