Wednesday 21 July 2021

javapoet: hello world application

In this post, I am going to explain how to generate simple HelloWorld class using javapoet library.

 

Step 1: Define main method specification.

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

methodBuilder.addStatement("$T.out.println($S)", System.class, "Hello World!!!");
MethodSpec mainMethod = methodBuilder.build();

 

Step 2: Define HelloWorld class spec and attach main method spec to it.

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

 

Step 3: Build java file by specifying the package.

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

Step 4: Write the generated class to System.out.

javaFile.writeTo(System.out);


Find the below working application.

 

HelloWorld.java

package com.sample.app;

import java.io.IOException;

import javax.lang.model.element.Modifier;

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

public class HelloWorld {

    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");

        methodBuilder.addStatement("$T.out.println($S)", System.class, "Hello World!!!");
        MethodSpec mainMethod = methodBuilder.build();

        String className = "HelloWorld";
        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 HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World!!!");
  }
}


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment