Tuesday 27 July 2021

Javapoet: Add generic super class

'ParameterizedTypeName' can be used to specify generic type arguments.

 

Example

TypeSpec myListSpec = TypeSpec.classBuilder("MyMap")
.superclass(ParameterizedTypeName.get(ClassName.get(HashMap.class), ClassName.get(Integer.class),ClassName.get(String.class)))

 

Above snippet generates below code snippet.

public final class MyMap extends HashMap<Integer, String> {
}

 

Find the below working application.

 

GenericSuperclassDemo.java

 

package com.sample.app;

import java.io.IOException;
import java.util.HashMap;

import javax.lang.model.element.Modifier;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;

public class GenericSuperclassDemo {

	public static void main(String args[]) throws IOException {
		TypeSpec myListSpec = TypeSpec.classBuilder("MyMap")
				.superclass(ParameterizedTypeName.get(ClassName.get(HashMap.class), ClassName.get(Integer.class),
						ClassName.get(String.class)))

				.addModifiers(Modifier.PUBLIC, Modifier.FINAL).build();

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

		javaFile.writeTo(System.out);
	}

}


Generated Code

package com.sample.app;

import java.lang.Integer;
import java.lang.String;
import java.util.HashMap;

public final class MyMap extends HashMap<Integer, String> {
} 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment