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?
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With