【问题标题】:JavaPoet Add Generic ParameterJavaPoet 添加通用参数
【发布时间】:2015-09-07 07:35:36
【问题描述】:

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

public <T extends MyClass> void doSomething(T t)

到目前为止我有:

MethodSpec.methodBuilder("doSomething")
        .addModifiers(Modifier.PUBLIC)
        .addTypeVariable(TypeVariableName.get("T", MyClass.class))
        .build()

EDIT这是上面代码生成的(不知道怎么加参数):

public <T extends Myclass> void doSomething()

【问题讨论】:

    标签: java code-generation javapoet


    【解决方案1】:

    将您生成的TypeVariableName 提取到一个变量中,以便您可以重复使用它的值

    TypeVariableName typeVariableName = TypeVariableName.get("T", MyClass.class);
    

    然后添加该类型的参数

    MethodSpec spec = MethodSpec.methodBuilder("doSomething")
                                .addModifiers(Modifier.PUBLIC)
                                .addTypeVariable(typeVariableName)
                                .addParameter(typeVariableName, "t") // you can also add modifiers
                                .build();
    

    【讨论】:

      【解决方案2】:

      如果你想传递一个Generic类型的结构,使用下面的方式。

      MethodSpec loadListInteger = MethodSpec.methodBuilder("loadListInteger")
                          .addModifiers(Modifier.PUBLIC)
                          .returns(void.class)
                          .addParameter(ParameterizedTypeName.get(List.class, Integer.class), "list")
                          .build();
      

      【讨论】:

        猜你喜欢
        • 2017-06-14
        • 2020-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 2015-05-20
        • 2021-03-26
        • 1970-01-01
        相关资源
        最近更新 更多