Use the syntax $argumentName:X where X is the format character and call CodeBlock.addNamed() with a map containing all argument keys in the format string. Argument names use characters in a-z, A-Z, 0-9, and _, and must start with a lowercase character.
Example
Map<String, Object> map = new HashMap<>();
map.put("name", "Krishna");
map.put("age", 32);
Builder codeBlock1 = CodeBlock.builder().addNamed("Hi, my name is $name:L and I am $age:L years old", map);
Above snippet generates below string.
Hi, my name is Krishna and I am 32 years old
Find the below working application.
CodeBlockNamedArgumentsDemo.java
package com.sample.app;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.lang.model.element.Modifier;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.CodeBlock.Builder;
public class CodeBlockNamedArgumentsDemo {
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");
Map<String, Object> map = new HashMap<>();
map.put("name", "Krishna");
map.put("age", 32);
Builder codeBlock1 = CodeBlock.builder().addNamed("Hi, my name is $name:L and I am $age:L years old", map);
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");
}
}
No comments:
Post a Comment