javapoet - how to implement "extends" and "implements"
Asked Answered
J

2

13

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.

Jot answered 11/1, 2016 at 6:17 Comment(0)
S
26

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

Sungsungari answered 11/1, 2016 at 7:24 Comment(3)
Thanks so much Jesse.Jot
I am creating a class implementing Serializable interface. How to write code to generate Serial version id?Jot
@urSus wanna send a pull request?Sungsungari
S
11

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 {
}
Sasser answered 28/4, 2016 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.