Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
jdyjjj committed Apr 20, 2022
1 parent 70ef9bd commit 3493782
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/main/java/com/squareup/javapoet/CodeBlock.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/squareup/javapoet/MethodSpec.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 51 additions & 0 deletions src/test/java/com/squareup/javapoet/MethodSpecTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> 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<String, Object> m = new HashMap<>();
m.put("field", "valueField");
Expand Down

0 comments on commit 3493782

Please sign in to comment.