Thursday, 22 July 2021

Javapoet: add fields to the class

'FieldSpec' is used to define a field.

 

Example

FieldSpec nameField = FieldSpec.builder(String.class, "name")
					.addModifiers(Modifier.PRIVATE)
					.build();

 

Above snippet generate following statement.

 

private String name;

 

Find the below working application.

 

FieldDemo.java

 

package com.sample.app;

import java.io.IOException;

import javax.lang.model.element.Modifier;

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

public class FieldDemo {

	public static void main(String args[]) throws IOException {
		FieldSpec nameField = FieldSpec.builder(String.class, "name")
			    .addModifiers(Modifier.PRIVATE)
			    .build();
		
		FieldSpec idField = FieldSpec.builder(int.class, "id")
			    .addModifiers(Modifier.PRIVATE)
			    .build();

		MethodSpec constructor = MethodSpec.constructorBuilder()
					.addModifiers(Modifier.PUBLIC)
					.addParameter(int.class, "id")
					.addParameter(String.class, "name")
					.addStatement("this.$N = $N", "id", "id")
					.addStatement("this.$N = $N", "name", "name").build();
		
		String className = "Employee";
		TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className);
		classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
		classBuilder.addMethod(constructor);
		classBuilder.addField(nameField).addField(idField);
		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;

public final class Employee {
  private String name;

  private int id;

  public Employee(int id, String name) {
    this.id = id;
    this.name = name;
  }
}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment