diff --git a/src/main/java/com/squareup/javapoet/CodeBlock.java b/src/main/java/com/squareup/javapoet/CodeBlock.java index 02542f58b..9cc047196 100644 --- a/src/main/java/com/squareup/javapoet/CodeBlock.java +++ b/src/main/java/com/squareup/javapoet/CodeBlock.java @@ -370,6 +370,12 @@ public Builder beginControlFlow(String controlFlow, Object... args) { return this; } + public Builder beginControlFlow(Object... args) { + add("{\n", args); + indent(); + return this; + } + /** * @param controlFlow the control flow construct and its code, such as "else if (foo == 10)". * Shouldn't contain braces or newline characters. diff --git a/src/main/java/com/squareup/javapoet/MethodSpec.java b/src/main/java/com/squareup/javapoet/MethodSpec.java index 67722c774..4efc241e0 100644 --- a/src/main/java/com/squareup/javapoet/MethodSpec.java +++ b/src/main/java/com/squareup/javapoet/MethodSpec.java @@ -474,6 +474,12 @@ public Builder beginControlFlow(String controlFlow, Object... args) { return this; } + public Builder beginControlFlow(Object... args) { + code.beginControlFlow(args); + return this; + + } + /** * @param codeBlock the control flow construct and its code, such as "if (foo == 5)". * Shouldn't contain braces or newline characters. diff --git a/src/test/java/com/squareup/javapoet/MethodSpecTest.java b/src/test/java/com/squareup/javapoet/MethodSpecTest.java index e180f200c..72ba05e0c 100644 --- a/src/test/java/com/squareup/javapoet/MethodSpecTest.java +++ b/src/test/java/com/squareup/javapoet/MethodSpecTest.java @@ -462,6 +462,57 @@ abstract static class AbstractClassWithPrivateAnnotation { + "}\n"); } + @Test public void controlBlockTestWithEmptyBeginBlock_1(){ + MethodSpec methodSpec = MethodSpec.methodBuilder("method") + .beginControlFlow() + .addStatement("int year = 2022") + .endControlFlow() + .beginControlFlow() + .addStatement("int month = 4") + .endControlFlow() + .beginControlFlow() + .addStatement("int day = 22") + .endControlFlow() + .build(); + + assertThat(methodSpec.toString()).isEqualTo("" + + "void method() {\n" + + " {\n" + + " int year = 2022;\n" + + " }\n" + + " {\n" + + " int month = 4;\n" + + " }\n" + + " {\n" + + " int day = 22;\n" + + " }\n" + + "}\n"); + } + + @Test public void controlBlockTestWithEmptyBeginBlock_2(){ + Map m = new HashMap<>(); + m.put("field", "valueField"); + m.put("threshold", "5"); + + MethodSpec methodSpec = MethodSpec.methodBuilder("method") + .beginControlFlow(named("if ($field:N > $threshold:L)", m)) + .nextControlFlow(named("else if ($field:N == $threshold:L)", m)) + .endControlFlow() + .beginControlFlow() + .endControlFlow() + .build(); + + assertThat(methodSpec.toString()).isEqualTo("" + + "void method() {\n" + + " if (valueField > 5) {\n" + + " } else if (valueField == 5) {\n" + + " }\n" + + " {\n" + + " }\n" + + "}\n"); + + } + @Test public void doWhileWithNamedCodeBlocks() { Map m = new HashMap<>(); m.put("field", "valueField");