1

How would I generate a method with the following signature?

public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type)
4

1 回答 1

2

在这里使用TypeVariableNamewithaddTypeVariable可能会有所帮助 -

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);

  }
}

注意- 我有我的MyClass,MyOtherClass并且MyInterface都在一个名为的包com也是实现它的类main()所在的位置。

使用的进口 -


生成输出为 -

package com;

public final class GenericImpl {
  public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type) {
  }
}
于 2017-01-29T14:57:20.993 回答