diff --git a/initializr-generator/src/main/java/io/spring/initializr/generator/language/CodeBlock.java b/initializr-generator/src/main/java/io/spring/initializr/generator/language/CodeBlock.java index ac0aebe6..78035ee9 100644 --- a/initializr-generator/src/main/java/io/spring/initializr/generator/language/CodeBlock.java +++ b/initializr-generator/src/main/java/io/spring/initializr/generator/language/CodeBlock.java @@ -264,7 +264,7 @@ public final class CodeBlock { private void addArgument(String format, char c, Object arg) { switch (c) { - case 'L' -> this.args.add(arg); + case 'L' -> this.args.add(arg(arg)); case 'S' -> this.args.add(argToString(arg)); case 'T' -> this.args.add(argToType(arg)); default -> throw new IllegalArgumentException( @@ -272,8 +272,15 @@ public final class CodeBlock { } } - private String argToString(Object o) { - return (o != null) ? String.valueOf(o) : null; + private Object arg(Object arg) { + if (arg instanceof CodeBlock code) { + this.imports.addAll(code.getImports()); + } + return arg; + } + + private String argToString(Object arg) { + return (arg != null) ? String.valueOf(arg) : null; } private String argToType(Object arg) { diff --git a/initializr-generator/src/test/java/io/spring/initializr/generator/language/CodeBlockTests.java b/initializr-generator/src/test/java/io/spring/initializr/generator/language/CodeBlockTests.java index ed50c54e..949ab993 100644 --- a/initializr-generator/src/test/java/io/spring/initializr/generator/language/CodeBlockTests.java +++ b/initializr-generator/src/test/java/io/spring/initializr/generator/language/CodeBlockTests.java @@ -179,6 +179,12 @@ class CodeBlockTests { assertThat(code.getImports()).isEmpty(); } + @Test + void codeBlockWithParameterCodeBlockAddsImports() { + CodeBlock code = CodeBlock.of("$L", CodeBlock.of("$T.truncate(myString)", ClassName.of(StringUtils.class))); + assertThat(code.getImports()).containsExactly(StringUtils.class.getName()); + } + private String writeJava(CodeBlock code) { return write(code, CodeBlock.JAVA_FORMATTING_OPTIONS); }