2

我使用JavaPoet创建 Java 代码。我定义了以下数组:

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

和一个构造函数:

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

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

前者不起作用。我想创建声明:

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

如何将数组分配给上一行中的语句?

4

2 回答 2

6

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());
  }
于 2015-10-10T16:19:21.173 回答
0

不知道会不会延迟。但我注意到“testArray”似乎是目标类中的一个语句,但作为 addStatement() 的一部分被称为 $N。要使 $N 起作用,它必须是代码中的 FieldSpec。

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

接着

MethodSpec constroctMethod = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
                    .addStatement("$T names", stringArray)
                    .addStatement("names = $N", testArr)
                    .build();
于 2020-08-31T14:56:33.023 回答