3

I use JavaPoet to create Java code. I defined the following array:

String[] testArr = new String[] {"1","2"};

and a constructor:

ArrayTypeName stringArray = ArrayTypeName.of(String.class);

MethodSpec constroctMethod = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
                    .addStatement("$T names", stringArray)
                    .addStatement("names = $N", testArr)
                    .build();

The former does not work. I want to create the statement:

String[] names = new String[] {"1","2"};

How can I assign an Array to a Statement like in the previous line?

Michael
  • 32,527
  • 49
  • 210
  • 370

2 Answers2

7

You can't use a MethodSpec to achive the string array initialization line, afaik. You need a simple CodeBlock and convert the array into a source code literal first.

Here is an example using Java 8 String.join to build the literal from your test array with JavaPoet 1.3 (see index based format expressions).

  @Test
  public void testStringArrayInit() {
    String expected = "java.lang.String[] names = new java.lang.String[] {\"1\",\"2\"}";
    String[] testArr = new String[] { "1", "2" };
    String literal = "{\"" + String.join("\",\"", testArr) + "\"}";
    ArrayTypeName stringArray = ArrayTypeName.of(String.class);
    CodeBlock block = CodeBlock.builder().add("$1T names = new $1T $2L", stringArray, literal).build();
    Assert.assertEquals(expected, block.toString());
  }
Sormuras
  • 8,491
  • 1
  • 38
  • 64
0

Not sure whether it is delayed. But I noticed that the "testArray" appears to be a statement in target class but is referred as $N as part of addStatement(). For the $N to work, it has to be a FieldSpec within your code.

FieldSpec testArray = FieldSpec.Builder(...).build();

and then

MethodSpec constroctMethod = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
                    .addStatement("$T names", stringArray)
                    .addStatement("names = $N", testArr)
                    .build();
ajoshi
  • 349
  • 2
  • 10