javajavapoet

How to generate code dynamically with javapoet? Change the method parameters


I'm trying to generate java code that depends on other variables. In this specific moment, I'm trying to generate the code depending on the protocol. So I can receive a CoapResponse object or a Response object form ( javax).

I don't know if it is possible instead of repeating all the code two times with the parameter different if I can reuse the same code and change only the variable in some way.

The code that I want to change is the following:


  MethodSpec payloadInterpreter = MethodSpec.methodBuilder("payloadInterpreter")
          .addModifiers(Modifier.PRIVATE)
          .addModifiers(Modifier.STATIC)
         .addParameter(Response.class, "getResponse")
          ....

And the Parameter it could be CoapResponse.class instead of Response.class.

I had the same problem with the Statements but I solved creating literals that use the information that the service received in runtime. An example:

if (MD.getMediatype().equals("JSON")){
      ReadOutDeclaration="JSONObject readout= null";
      GetReadOut="readout = getResponse.readEntity(JSONObject.class)";

and then:

 MethodSpec payloadInterpreter = MethodSpec.methodBuilder("payloadInterpreter")
     .addModifiers(Modifier.PRIVATE)
     .addModifiers(Modifier.STATIC)
     .addParameter(Response.class, "getResponse")
     .addStatement("$L",ReadOutDeclaration)
     .beginControlFlow("try")
     .addStatement("$L", GetReadOut)
     .addStatement("System.out.println(\"Provider Response payload: \" + $L)",ReadOutPrint)   

I don't know if I can do something similar to this with the parameters or even if there are other ways to do change the generation dynamically. Thank you in advance.


Solution

  • May be this helps:

    MethodSpec.Builder payloadInterpreterMethod = MethodSpec.methodBuilder("payloadInterpreter")
              .addModifiers(Modifier.PRIVATE)
              .addModifiers(Modifier.STATIC);
    if (condition) {
      payloadInterpreterMethod.addParameter(Response.class, "getResponse");
    } else {
      payloadInterpreterMethod.addParameter(CoapResponse.class, "getResponse");
    }
    

    and once you want to add it to the TypeSpec, use:

    payloadInterpreterMethod.build()