Tuesday, 27 July 2021

Javapoet: Add generic type to a class

Step 1: Define Type variables.

TypeVariableName typeVariableName1 = TypeVariableName.get("T");
TypeVariableName typeVariableName2 = TypeVariableName.get("U");

 

Step 2: Add type variables to the class.

TypeSpec helloWorldTypeSpec = TypeSpec.classBuilder("Test")
.addTypeVariables(Arrays.asList(typeVariableName1, typeVariableName2)).addField(keyField)
.addField(idField).build();

 

Find the below working application.

 

AddGenericTypeToAClass.java

 

package com.sample.app;

import java.io.IOException;
import java.util.Arrays;

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

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

		TypeVariableName typeVariableName1 = TypeVariableName.get("T");
		TypeVariableName typeVariableName2 = TypeVariableName.get("U");
		FieldSpec idField = FieldSpec.builder(typeVariableName1, "id").build();
		FieldSpec keyField = FieldSpec.builder(typeVariableName2, "key").build();

		TypeSpec helloWorldTypeSpec = TypeSpec.classBuilder("Test")
				.addTypeVariables(Arrays.asList(typeVariableName1, typeVariableName2)).addField(keyField)
				.addField(idField).build();

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

		javaFile.writeTo(System.out);
	}

}

 

Generated code

package com.sample.app;

class Test<T, U> {
  U key;

  T id;
}

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment