Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Javapoet: implement an interface

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×