Allow CodeBlock to be used by $L

This commit is contained in:
Stephane Nicoll 2023-06-08 10:53:23 +02:00
parent 4c77196504
commit d22201b2d6
2 changed files with 24 additions and 2 deletions

View File

@ -31,7 +31,8 @@ import org.springframework.util.ClassUtils;
* are supported:
* <ul>
* <li>{@code $L} emits a literal value. Arguments for literals may be plain String,
* primitives, or any type where the {@code toString()} representation can be used.
* primitives, another {@code CodeBlock}, or any type where the {@code toString()}
* representation can be used.
* <li>{@code $S} escapes the value as a string, wraps it with double quotes, and emits
* that. Emit {@code "null"} if the value is {@code null}. Does not handle multi-line
* strings.
@ -86,7 +87,15 @@ public final class CodeBlock {
int argIndex = 0;
for (String part : this.parts) {
switch (part) {
case "$L" -> writer.print(String.valueOf(this.args.get(argIndex++)));
case "$L" -> {
Object value = this.args.get(argIndex++);
if (value instanceof CodeBlock code) {
code.write(writer, options);
}
else {
writer.print(String.valueOf(value));
}
}
case "$S" -> {
String value = (String) this.args.get(argIndex++);
String valueToEmit = (value != null) ? quote(value) : "null";

View File

@ -86,6 +86,19 @@ class CodeBlockTests {
assertThat(writeJava(code)).isEqualTo("return myUtil.truncate(myString)");
}
@Test
void codeBlockWithLiteralPlaceHolderUsingCodeBlock() {
CodeBlock code = CodeBlock.of("return myUtil.add($L, $L)", CodeBlock.of("1"), CodeBlock.of("2"));
assertThat(writeJava(code)).isEqualTo("return myUtil.add(1, 2)");
}
@Test
void codeBlockWithLiteralPlaceHolderUsingNestedCodeBlock() {
CodeBlock code = CodeBlock.of("return myUtil.add($L)",
CodeBlock.of("$L, $L", CodeBlock.of("1"), CodeBlock.of("2")));
assertThat(writeJava(code)).isEqualTo("return myUtil.add(1, 2)");
}
@Test
void codeBlockWithDollarSignPlaceholder() {
CodeBlock code = CodeBlock.of("// $$ allowed, that's $$$L.", 25);