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

491 views Asked by At

How would I generate a method with the following signature?

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

Problem: Not sure how to add return type : ServiceA<? extends ServiceB>

Assuming I have FQCN for ServiceA and ServiceB.

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

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

The above code generates the following code:

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

Any lead would be appreciated.

1

There are 1 answers

0
abhilash_goyal On

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

Following code worked.

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