Tuesday, 27 July 2021

Javapoet: Add a super class

‘TypeSpec.Builder.superclass()’ is used to specify a super class.

 

Example

TypeSpec myListSpec = TypeSpec.classBuilder("MyList")
		.superclass(ArrayList.class)
		.addModifiers(Modifier.PUBLIC, Modifier.FINAL).build();

 

Above snippet generates below code.

public final class MyList extends ArrayList {
}

Find the below working application.

 

SuperclassDemo.java

package com.sample.app;

import java.io.IOException;
import java.util.ArrayList;

import javax.lang.model.element.Modifier;

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

public class SuperclassDemo {

	public static void main(String args[]) throws IOException {
		TypeSpec myListSpec = TypeSpec.classBuilder("MyList").superclass(ArrayList.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.util.ArrayList;

public final class MyList extends ArrayList {
}


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment