1

How would I generate a method with the following signature?

public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type)
M. Reza Nasirloo
  • 16,434
  • 2
  • 29
  • 41

1 Answers1

2

Using a TypeVariableName along with addTypeVariable might help here -

import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier;
import java.io.IOException;

public class AttemptGeneric {

  public static void main(String[] args) throws IOException {

    ClassName myClass = ClassName.get("com", "MyClass");
    ClassName myOtherClass = ClassName.get("com", "MyOtherClass");
    ClassName myInterface = ClassName.get("com", "MyInterface");
    TypeVariableName typeVariableName = TypeVariableName.get("T", myClass);

    MethodSpec methodSpec = MethodSpec.methodBuilder("someMethod")
            .returns(myOtherClass)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addTypeVariable(typeVariableName.withBounds(myInterface))
            .addParameter(typeVariableName,"type")
            .build();


    TypeSpec genericClass = TypeSpec.classBuilder("GenericImpl")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(methodSpec)
            .build();

    JavaFile javaFile = JavaFile.builder("com", genericClass)
            .build();

    javaFile.writeTo(System.out);

  }
}

Note - I've my MyClass, MyOtherClass and MyInterface all within a package named com which is where the class implementing this main() also resides.

Imports used -


Generates output as --

package com;

public final class GenericImpl {
  public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type) {
  }
}
Naman
  • 27,789
  • 26
  • 218
  • 353