From 40ec07c80785a9affd81f7e7d2fbc9abd5c6d1ac Mon Sep 17 00:00:00 2001 From: devashish Date: Fri, 24 Jan 2020 23:34:58 +0530 Subject: [PATCH] Added support for multiline comments --- .../com/squareup/javapoet/MethodSpec.java | 7 +++- .../com/squareup/javapoet/MethodSpecTest.java | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/squareup/javapoet/MethodSpec.java b/src/main/java/com/squareup/javapoet/MethodSpec.java index 2284ef512..80334ca73 100644 --- a/src/main/java/com/squareup/javapoet/MethodSpec.java +++ b/src/main/java/com/squareup/javapoet/MethodSpec.java @@ -461,7 +461,12 @@ public Builder addCode(CodeBlock codeBlock) { } public Builder addComment(String format, Object... args) { - code.add("// " + format + "\n", args); + String[] lines = format.split("\\R"); + code.add("/*\n"); + for (String line : lines) { + code.add("* " + line + "\n"); + } + code.add("**/\n"); return this; } diff --git a/src/test/java/com/squareup/javapoet/MethodSpecTest.java b/src/test/java/com/squareup/javapoet/MethodSpecTest.java index b768351b5..f59b26653 100644 --- a/src/test/java/com/squareup/javapoet/MethodSpecTest.java +++ b/src/test/java/com/squareup/javapoet/MethodSpecTest.java @@ -456,6 +456,44 @@ static void staticMethod() { "}\n"); } + @Test public void multilineComments() { + MethodSpec main = MethodSpec.methodBuilder("main") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .returns(void.class) + .addParameter(String[].class, "args") + .addComment("Hello\nmultiline\ncomments!") + .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") + .build(); + + assertThat(main.toString()).isEqualTo("" + + "public static void main(java.lang.String[] args) {\n" + + " /*\n" + + " * Hello\n" + + " * multiline\n" + + " * comments!\n" + + " **/\n" + + " java.lang.System.out.println(\"Hello, JavaPoet!\");\n" + + "}\n"); + } + + @Test public void singleLineComments() { + MethodSpec main = MethodSpec.methodBuilder("main") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .returns(void.class) + .addParameter(String[].class, "args") + .addComment("Hello single line comments!") + .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") + .build(); + + assertThat(main.toString()).isEqualTo("" + + "public static void main(java.lang.String[] args) {\n" + + " /*\n" + + " * Hello single line comments!\n" + + " **/\n" + + " java.lang.System.out.println(\"Hello, JavaPoet!\");\n" + + "}\n"); + } + private static CodeBlock named(String format, Map args){ return CodeBlock.builder().addNamed(format, args).build(); }