javascalacode-generationjavapoet

Generate a call to a method with a variable number of arguments


I'm using JavaPoet to generate classes given a list of fields.

Generating a constructor that takes this list of fields and turns it into a list of parameters is fairly straightforward with something like the following:

val constructor = MethodSpec.constructorBuilder()
for ((fieldName, typeName) <- fields) {
  constructor.addParameter(typeName, fieldName)
}

I would also like to generate a static method that instantiates a new object of the generated class, which requires me to generate a code block that uses the aforementioned list of fields.

Currently, I'm achieving this with something like the following:

method
  .addStatement(s"return new $$T(${fields.map(_._1).mkString(", ")})", className)

It works, but I was wondering if there was a more "idiomatic" way to use JavaPoet to build a list of arguments with the built-in templating support.


Solution

  • In order to avoid mixing Scala's interpolation and JavaPoet's templating it looks like the best way to achieve this is by making a CodeBlock that contains the parameter list and embedding it in the code with a template, as in the following example:

    val params = fields.map { case (name, _) => CodeBlock.of(name) }
    val paramList = CodeBlock.join(params.asJava)
    method.addStatement("return new $T($L)", className, paramList)
    

    The template here makes use of the $L placeholder that will be replaced by a literal (in this case, the assembled list of parameters).