4

I want to generate a class that extends other class using JavaPoet.

For example I have this class:

@MyAnnotation
public class ClassA {
  public ClassA(String paramA, int paramB) {
     // some code
  }
} 

and I want to generate new class like this one:

public class Generated_ClassA extends ClassA {
  public Generated_ClassA (String paramA, int paramB) {
     super(paramA, paramB);
  }
} 

However, I don't see any ready-to-use API in JavaPoet to create constructors which are calling superclass constructors. How it is possible to do this and what are the best practices?

vsminkov
  • 9,774
  • 1
  • 35
  • 49
radzio
  • 2,592
  • 3
  • 21
  • 31

1 Answers1

6

You can do it by using MethodSpec.Builder#addStatement

MethodSpec.constructorBuilder()
          .addModifiers(Modifier.PUBLIC)
          .addParameter(String.class, "paramA")
          .addParameter(Integer.TYPE, "paramB")
          .addStatement("super(paramA, paramB)")
          .build();

You can also also use MethodSpec.Builder#addCode and build same code using CodeBlock.Builder#addStatement but unfortunately AFAIK there is no specific builders available for calling super.

vsminkov
  • 9,774
  • 1
  • 35
  • 49