【问题标题】:JavaPoet Generic ParameterJavaPoet 通用参数
【发布时间】:2017-06-14 10:57:19
【问题描述】:

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

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

【问题讨论】:

    标签: java code-generation annotation-processing javapoet


    【解决方案1】:

    在这里使用 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 的包中,这是实现此 @ 的类987654331@ 也驻留。

    使用的进口 -


    生成输出为 --

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

    【讨论】:

    • 有点晚了,但谢谢,这里是问题的链接github.com/square/javapoet/issues/543
    • @Pedram - wc。我相信你太快把它作为一个问题发布了。 :)
    • 是的,我有最后期限要赶上 ;)
    猜你喜欢
    • 2015-09-07
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多