Tuesday, 27 July 2021

Javapoet: implement an interface

'TypeSpec.Builder.addSuperinterface()' is used to specify the interfaces implemented by this class.

 

Example

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

 

Above snippet generates below code.

public final class MyList extends ArrayList implements Cloneable, Serializable {
}

 

Find the below working application.

 

ImplementInterface.java

package com.sample.app;

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

import javax.lang.model.element.Modifier;

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

public class ImplementInterface {

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

public final class MyList extends ArrayList implements Cloneable, Serializable {
}

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment