Javapoet and generic class declarations

480 Views Asked by At

How do I get javapoet to generate the java code below?

class B<T extends U> implements A<T> {

}

I know there is a class WildcardTypeName, but it can only generate? extends U or ? super U.

what I want is T extends U

1

There are 1 best solutions below

0
On BEST ANSWER

In your description, U and A should be exist class. You can use following code.

public static void main(String[] args) throws IOException {
  TypeVariableName t = TypeVariableName.get("T").withBounds(U.class);
  TypeSpec type = TypeSpec.classBuilder("B")
      .addTypeVariable(t)
      .addSuperinterface(ParameterizedTypeName.get(ClassName.get(A.class), t))
      .build();
  JavaFile.builder("", type).build().writeTo(System.out);
}

Its output is

import yourpackage.A;
import yourpackage.U;

class B<T extends U> implements A<T> {
}