Friday, 23 July 2021

Javapoet: Add an annotation

‘addAnnotaiton’ method is used to add an annotation.

 

Example

MethodSpec toStringSpec = MethodSpec.methodBuilder("toString").addModifiers(Modifier.PUBLIC)
            .addStatement("return $S", "Hello World application").returns(String.class)
            .addAnnotation(Override.class).build();

 

Above snippet generates following code.

@Override
public String toString() {
  return "Hello World application";
}

 

Find the below working application.

 

AddAnnotationDemo.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 AddAnnotationDemo {

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

    MethodSpec toStringSpec = MethodSpec.methodBuilder("toString").addModifiers(Modifier.PUBLIC)
        .addStatement("return $S", "Hello World application").returns(String.class)
        .addAnnotation(Override.class).build();

    String className = "HelloWorld";
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className);
    classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    classBuilder.addMethod(toStringSpec);
    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.Override;
import java.lang.String;

public final class HelloWorld {
  @Override
  public String toString() {
    return "Hello World application";
  }
}


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment