mirror of
https://gitee.com/dcren/initializr.git
synced 2025-04-05 17:38:06 +08:00
Allow CodeBlock to be used by $L
This commit is contained in:
parent
4c77196504
commit
d22201b2d6
@ -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";
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user