Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign an Array to a MethodSpec Statement in JavaPoet?

Tags:

java

javapoet

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?

like image 722
confile Avatar asked Jul 27 '26 19:07

confile


1 Answers

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());
  }
like image 86
Sormuras Avatar answered Jul 30 '26 09:07

Sormuras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!