Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javapoet - how to implement "extends" and "implements"

Tags:

java

javapoet

Using Javapoet, how to implement the following:

  1. class A extends class B

  2. class C implements Interface D

In the javadoc, it is mentioned how to create interfaces.

like image 745
KCMS Avatar asked Jan 11 '16 06:01

KCMS


2 Answers

Use TypeSpec.Builder.superclass() for extends, and TypeSpec.Builder.addSuperinterface() for implements.

like image 164
Jesse Wilson Avatar answered Nov 06 '22 14:11

Jesse Wilson


Suppose you want to generate a Dummy class that extends Exception class and implements the Serializable interface. The generate code is:

...
TypeSpec typeSpec = TypeSpec.classBuilder("Dummy")
  .addSuperinterface(Serializable.class) 
  .superclass(Exception.class) 
  .build();

JavaFile javaFile = JavaFile.builder("sample.javapoet", typeSpec).build();
...

And the generated code will be:

package sample.javapoet;

import java.io.Serializable;
import java.lang.Exception;

class Hoge extends Exception implements Serializable {
}
like image 36
xcesco Avatar answered Nov 06 '22 16:11

xcesco