如何在Java Poet中添加带参数的函数返回类型

huangapple go评论105阅读模式
英文:

How to add a parameterized return type of function in Java Poet

问题

public ServiceA<? extends ServiceB> anyFunctionName() {
    // code
}

Problem:
不确定如何添加返回类型:`ServiceA<? extends ServiceB>`

假设我有ServiceA和ServiceB的完全限定类名

我尝试的代码如下但不起作用

MethodSpec.Builder builder =
        MethodSpec.methodBuilder("anyFunctionName")
            .addModifiers(Modifier.PRIVATE)
            .returns(ParameterSpec.builder(ParameterizedTypeName.get(
                    ClassName.bestGuess("com.learn.ServiceA"),
                    WildcardTypeName.subtypeOf(Object.class),
                    ClassName.bestGuess("com.learn.ServiceB")).build());

请注意,上述内容是您提供的原始文本的翻译部分。如果您有任何其他翻译需求,请随时提问。

英文:

How would I generate a method with the following signature?

public ServiceA&lt;? extends ServiceB&gt; anyFunctionName() {
    // code
}

Problem:
Not sure how to add return type : ServiceA&lt;? extends ServiceB&gt;

Assuming I have FQCN for ServiceA and ServiceB.

What I am trying is code below, but does'nt work.

 MethodSpec.Builder builder =
            MethodSpec.methodBuilder(&quot;anyFunctionName&quot;)
                .addModifiers(Modifier.PRIVATE)
  .returns(ParameterSpec.builder(ParameterizedTypeName.get(
                    ClassName.bestGuess(&quot;com.learn.ServiceA&quot;),
                    WildcardTypeName.subtypeOf(Object.class),
                    ClassName.bestGuess(&quot;com.learn.ServiceB&quot;)).build());

The above code generates the following code:

public ServiceA&lt;? , ServiceB&gt; anyFunctionName() {
        // code
    }

Any lead would be appreciated.

答案1

得分: 1

非常感谢 @Michael 指出了我所犯的错误。

以下代码有效。

MethodSpec.Builder builder =
    MethodSpec.methodBuilder("anyFunctionName")
        .addModifiers(Modifier.PRIVATE)
        .returns(ParameterizedTypeName.get(
            ClassName.bestGuess("com.learn.ServiceA"),
            WildcardTypeName.subtypeOf(ClassName.bestGuess("com.learn.ServiceB")));
英文:

Thanks a lot, @Michael for pointing out the mistake I was doing.

Following code worked.

MethodSpec.Builder builder =
            MethodSpec.methodBuilder(&quot;anyFunctionName&quot;)
                .addModifiers(Modifier.PRIVATE)
  .returns(ParameterizedTypeName.get(
                    ClassName.bestGuess(&quot;com.learn.ServiceA&quot;),
                    WildcardTypeName.subtypeOf(ClassName.bestGuess(&quot;com.learn.ServiceB&quot;)));

huangapple
  • 本文由 发表于 2020年9月8日 17:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63791384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定