JavaPoet通用参数

时间:2017-01-29 00:20:56

标签: java code-generation annotation-processing javapoet

如何生成具有以下签名的方法?

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

1 个答案:

答案 0 :(得分:2)

使用TypeVariableNameaddTypeVariable可能会有所帮助 -

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

  }
}

注意 - 我的MyClassMyOtherClassMyInterface都位于名为com的包中这也是实现此main()的类所在的位置。

使用的进口货物 -

生成输出为 -

package com;

public final class GenericImpl {
  public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type) {
  }
}