### Example Generated HelloWorld Class (Java) Source: https://github.com/square/javapoet/blob/master/README.md Displays the simple 'HelloWorld' Java class that serves as the target output for the subsequent JavaPoet code generation example. It shows the structure and content of the file to be created. ```java package com.example.helloworld; public final class HelloWorld { public static void main(String[] args) { System.out.println("Hello, JavaPoet!"); } } ``` -------------------------------- ### Example Java Code with Inter-Method Calls Source: https://github.com/square/javapoet/blob/master/README.md Provides a simple Java example where one method (`byteToHex`) calls another method (`hexDigit`). This serves as the target structure for demonstrating how to generate such code using JavaPoet's $N placeholder. ```Java public String byteToHex(int b) { char[] result = new char[2]; result[0] = hexDigit((b >>> 4) & 0xf); result[1] = hexDigit(b & 0xf); return new String(result); } public char hexDigit(int i) { return (char) (i < 10 ? i + '0' : i - 10 + 'a'); } ``` -------------------------------- ### Generated Dynamic Method Example (Java) Source: https://github.com/square/javapoet/blob/master/README.md The resulting Java code generated by calling the `computeRange` method with specific parameters, showing how the dynamic values are embedded into the generated source code. ```Java int multiply10to20() { int result = 1; for (int i = 10; i < 20; i++) { result = result * i; } return result; } ``` -------------------------------- ### Generated Code with String Literals from $S Example Source: https://github.com/square/javapoet/blob/master/README.md Shows the resulting Java code generated by the previous JavaPoet snippet using the `$S` format specifier. It confirms that string literals are correctly emitted with surrounding quotation marks. ```java public final class HelloWorld { String slimShady() { return "slimShady"; } String eminem() { return "eminem"; } String marshallMathers() { return "marshallMathers"; } } ``` -------------------------------- ### Generated Code with Generic Type from $T and ParameterizedTypeName Example Source: https://github.com/square/javapoet/blob/master/README.md Displays the Java code generated by the previous JavaPoet snippet using `$T` with `ParameterizedTypeName`. It shows the generated method using the generic `List` type and the necessary imports for `List`, `ArrayList`, and `Hoverboard`. ```java package com.example.helloworld; import com.mattel.Hoverboard; import java.util.ArrayList; import java.util.List; public final class HelloWorld { List beyond() { List result = new ArrayList<>(); result.add(new Hoverboard()); result.add(new Hoverboard()); result.add(new Hoverboard()); return result; } } ``` -------------------------------- ### Generated Code with Date Type from $T Example Source: https://github.com/square/javapoet/blob/master/README.md Displays the Java code generated by the previous JavaPoet snippet using `$T` with `Date.class`. It shows the generated method using the `Date` type and the automatically added import statement for `java.util.Date`. ```java package com.example.helloworld; import java.util.Date; public final class HelloWorld { Date today() { return new Date(); } } ``` -------------------------------- ### Generated Code with Custom Type from $T and ClassName Example Source: https://github.com/square/javapoet/blob/master/README.md Presents the Java code generated by the previous JavaPoet snippet using `$T` with `ClassName`. It shows the generated method using the custom `Hoverboard` type and the automatically added import statement for `com.mattel.Hoverboard`. ```java package com.example.helloworld; import com.mattel.Hoverboard; public final class HelloWorld { Hoverboard tomorrow() { return new Hoverboard(); } } ``` -------------------------------- ### Handle JavaPoet API Change: Field to Method Source: https://github.com/square/javapoet/blob/master/README.md Highlights a common API change encountered when migrating to Palantir's JavaPoet, showing an example where accessing a property like `packageName` changes from a field access to a method call `packageName()`. ```diff - javaFile.packageName + javaFile.packageName() ``` -------------------------------- ### Generating Dynamic Method with JavaPoet (`$L` Literals) (Java) Source: https://github.com/square/javapoet/blob/master/README.md Refines the dynamic method generation example by using the `$L` format specifier to insert literal values (primitives, strings) into statements and control flow conditions, improving readability and safety compared to string concatenation. ```Java private MethodSpec computeRange(String name, int from, int to, String op) { return MethodSpec.methodBuilder(name) .returns(int.class) .addStatement("int result = 0") .beginControlFlow("for (int i = $L; i < $L; i++)", from, to) .addStatement("result = result $L i", op) .endControlFlow() .addStatement("return result") .build(); } ``` -------------------------------- ### Handling Try/Catch with JavaPoet `nextControlFlow` (Java) Source: https://github.com/square/javapoet/blob/master/README.md Shows how to generate `try/catch` blocks using `beginControlFlow` for the `try` block, `nextControlFlow` for the `catch` clause, and `endControlFlow` in JavaPoet. ```Java MethodSpec main = MethodSpec.methodBuilder("main") .beginControlFlow("try") .addStatement("throw new Exception($S)", "Failed") .nextControlFlow("catch ($T e)", Exception.class) .addStatement("throw new $T(e)", RuntimeException.class) .endControlFlow() .build(); ``` -------------------------------- ### Defining a Constructor with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Illustrates how to build a public constructor using `MethodSpec.constructorBuilder()`, add a parameter, and include a statement in its body using JavaPoet. Shows how to add the constructor and a corresponding field to a class. ```Java MethodSpec flux = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(String.class, "greeting") .addStatement("this.$N = $N", "greeting", "greeting") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC) .addField(String.class, "greeting", Modifier.PRIVATE, Modifier.FINAL) .addMethod(flux) .build(); ``` ```Java public class HelloWorld { private final String greeting; public HelloWorld(String greeting) { this.greeting = greeting; } } ``` -------------------------------- ### Generate HelloWorld Class using JavaPoet (Java) Source: https://github.com/square/javapoet/blob/master/README.md Provides the Java code using the JavaPoet library to programmatically define and generate the 'HelloWorld' class shown previously. It demonstrates building MethodSpec and TypeSpec objects and writing the resulting JavaFile. ```java MethodSpec main = MethodSpec.methodBuilder("main") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(String[].class, "args") .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(main) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); javaFile.writeTo(System.out); ``` -------------------------------- ### Code Block Formatting: Named Arguments in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Explains and shows how to use named arguments for formatting code blocks in JavaPoet. Placeholders use the syntax $argumentName:X and arguments are provided via a Map to the CodeBlock.addNamed() method. ```Java Map map = new LinkedHashMap<>(); map.put("food", "tacos"); map.put("count", 3); CodeBlock.builder().addNamed("I ate $count:L $food:L", map) ``` -------------------------------- ### Generated Java Code with Static Imports Source: https://github.com/square/javapoet/blob/master/README.md Shows the resulting Java code file generated by the preceding JavaPoet code, illustrating how the static imports are applied and how the method calls are simplified. ```Java package com.example.helloworld; import static com.mattel.Hoverboard.Boards.*; import static com.mattel.Hoverboard.createNimbus; import static java.util.Collections.*; import com.mattel.Hoverboard; import java.util.ArrayList; import java.util.List; class HelloWorld { List beyond() { List result = new ArrayList<>(); result.add(createNimbus(2000)); result.add(createNimbus("2001")); result.add(createNimbus(THUNDERBOLT)); sort(result); return result.isEmpty() ? emptyList() : result; } } ``` -------------------------------- ### Handling If/Else If/Else with JavaPoet `nextControlFlow` (Java) Source: https://github.com/square/javapoet/blob/master/README.md Shows how to generate complex control flow structures like `if/else if/else` using `beginControlFlow`, `nextControlFlow` (for `else if` and `else`), and `endControlFlow` in JavaPoet. ```Java MethodSpec main = MethodSpec.methodBuilder("main") .addStatement("long now = $T.currentTimeMillis()", System.class) .beginControlFlow("if ($T.currentTimeMillis() < now)", System.class) .addStatement("$T.out.println($S)", System.class, "Time travelling, woo hoo!") .nextControlFlow("else if ($T.currentTimeMillis() == now)", System.class) .addStatement("$T.out.println($S)", System.class, "Time stood still!") .nextControlFlow("else") .addStatement("$T.out.println($S)", System.class, "Ok, time still moving forward") .endControlFlow() .build(); ``` -------------------------------- ### Using JavaPoet `addStatement` and Control Flow (Java) Source: https://github.com/square/javapoet/blob/master/README.md Illustrates using `addStatement` for automatic semicolons and newlines, and `beginControlFlow`/`endControlFlow` for handling braces and indentation in generated code, simplifying formatting compared to `addCode`. ```Java MethodSpec main = MethodSpec.methodBuilder("main") .addStatement("int total = 0") .beginControlFlow("for (int i = 0; i < 10; i++)") .addStatement("total += i") .endControlFlow() .build(); ``` -------------------------------- ### Code Block Formatting: Relative Arguments in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Shows how to format code blocks in JavaPoet using relative arguments with the CodeBlock.add() method. Arguments are provided sequentially and mapped to placeholders like $L in the format string. ```Java CodeBlock.builder().add("I ate $L $L", 3, "tacos") ``` -------------------------------- ### Configuring Sonatype Nexus Server in Maven Settings (XML) Source: https://github.com/square/javapoet/blob/master/RELEASING.md This XML snippet configures the Sonatype Nexus staging server credentials in the Maven `settings.xml` file, allowing Maven to deploy artifacts to the staging repository. It requires your Nexus username and password. ```XML sonatype-nexus-staging your-nexus-username your-nexus-password ``` -------------------------------- ### Creating Interfaces with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates building a public interface, adding a public static final field with an initializer, and adding a public abstract method using JavaPoet. Notes that required interface modifiers are omitted in the generated code as they are default. ```Java TypeSpec helloWorld = TypeSpec.interfaceBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC) .addField(FieldSpec.builder(String.class, "ONLY_THING_THAT_IS_CONSTANT") .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) .initializer("$S", "change") .build()) .addMethod(MethodSpec.methodBuilder("beep") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .build()) .build(); ``` ```Java public interface HelloWorld { String ONLY_THING_THAT_IS_CONSTANT = "change"; void beep(); } ``` -------------------------------- ### Code Block Formatting: Positional Arguments in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates formatting code blocks using positional arguments in JavaPoet. An integer index (1-based) before the placeholder (e.g., $2L) specifies which argument from the list should be used. ```Java CodeBlock.builder().add("I ate $2L $1L", "tacos", 3) ``` -------------------------------- ### Replace Square JavaPoet Imports with Palantir Source: https://github.com/square/javapoet/blob/master/README.md Provides a shell command using `sed` to automatically replace package imports from `com.squareup.javapoet` to `com.palantir.javapoet` in Java and Kotlin source files during the migration process. ```bash sed -i "" \ 's/com.squareup.javapoet.\([A-Za-z]*\)/com.palantir.javapoet.\1/g' \ `find . -name "*.kt" -or -name "*.java"` ``` -------------------------------- ### Adding Raw Code with JavaPoet `addCode` (Java) Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates adding a block of code to a method using the `addCode` method. This approach requires manual handling of formatting, including semicolons, newlines, and indentation. ```Java MethodSpec main = MethodSpec.methodBuilder("main") .addCode("" + "int total = 0;\n" + "for (int i = 0; i < 10; i++) {\n" + " total += i;\n" + "}\n") .build(); ``` -------------------------------- ### Defining Maven Release Alias in Shell (.rc) (Shell) Source: https://github.com/square/javapoet/blob/master/RELEASING.md This shell alias defines a shortcut `mvn-release` that combines several Maven commands necessary for preparing and performing a release, including cleaning, building source and Javadoc jars, verifying, cleaning the release state, preparing the release, and performing the release. ```Shell alias mvn-release='mvn clean source:jar javadoc:jar verify && mvn clean release:clean && mvn release:prepare release:perform' ``` -------------------------------- ### Generated Try/Catch Structure (Java) Source: https://github.com/square/javapoet/blob/master/README.md The resulting Java code generated by the previous JavaPoet snippet, demonstrating the `try/catch` structure produced by using `beginControlFlow`, `nextControlFlow` (for catch), and `endControlFlow`. ```Java void main() { try { throw new Exception("Failed"); } catch (Exception e) { throw new RuntimeException(e); } } ``` -------------------------------- ### Defining Class Fields with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Shows how to add fields to a class using both `FieldSpec.builder()` and the `TypeSpec.addField()` helper. Demonstrates adding modifiers and using initializers with `String.format()` syntax. ```Java FieldSpec android = FieldSpec.builder(String.class, "android") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC) .addField(android) .addField(String.class, "robot", Modifier.PRIVATE, Modifier.FINAL) .build(); ``` ```Java public class HelloWorld { private final String android; private final String robot; } ``` ```Java FieldSpec android = FieldSpec.builder(String.class, "android") .addModifiers(Modifier.PRIVATE, Modifier.FINAL) .initializer("$S + $L", "Lollipop v.", 5.0d) .build(); ``` ```Java private final String android = "Lollipop v." + 5.0; ``` -------------------------------- ### Declaring Method Parameters with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Explains how to add parameters to a method using both the `ParameterSpec.builder()` for more control (e.g., annotations) and the convenient `MethodSpec.addParameter()` helper methods. ```Java ParameterSpec android = ParameterSpec.builder(String.class, "android") .addModifiers(Modifier.FINAL) .build(); MethodSpec welcomeOverlords = MethodSpec.methodBuilder("welcomeOverlords") .addParameter(android) .addParameter(String.class, "robot", Modifier.FINAL) .build(); ``` ```Java void welcomeOverlords(final String android, final String robot) { } ``` -------------------------------- ### Generating Code with Static Imports using JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to use JavaPoet's addStaticImport method to include static imports in the generated Java source file. It shows importing specific members and entire classes/enums using the '*' wildcard. ```Java ... ClassName namedBoards = ClassName.get("com.mattel", "Hoverboard", "Boards"); MethodSpec beyond = MethodSpec.methodBuilder("beyond") .returns(listOfHoverboards) .addStatement("$T result = new $T<>()", listOfHoverboards, arrayList) .addStatement("result.add($T.createNimbus(2000))", hoverboard) .addStatement("result.add($T.createNimbus("2001"))", hoverboard) .addStatement("result.add($T.createNimbus($T.THUNDERBOLT))", hoverboard, namedBoards) .addStatement("$T.sort(result)", Collections.class) .addStatement("return result.isEmpty() ? $T.emptyList() : result", Collections.class) .build(); TypeSpec hello = TypeSpec.classBuilder("HelloWorld") .addMethod(beyond) .build(); JavaFile.builder("com.example.helloworld", hello) .addStaticImport(hoverboard, "createNimbus") .addStaticImport(namedBoards, "*") .addStaticImport(Collections.class, "*") .build(); ``` -------------------------------- ### Generated If/Else If/Else Structure (Java) Source: https://github.com/square/javapoet/blob/master/README.md The resulting Java code generated by the previous JavaPoet snippet, demonstrating the structure produced by using `beginControlFlow`, `nextControlFlow`, and `endControlFlow` for conditional logic. ```Java void main() { long now = System.currentTimeMillis(); if (System.currentTimeMillis() < now) { System.out.println("Time travelling, woo hoo!"); } else if (System.currentTimeMillis() == now) { System.out.println("Time stood still!"); } else { System.out.println("Ok, time still moving forward"); } } ``` -------------------------------- ### Adding JavaPoet Dependency (Gradle Groovy) Source: https://github.com/square/javapoet/blob/master/README.md Provides the Groovy snippet required to add the JavaPoet library as a dependency in a Gradle project's build file. ```groovy compile 'com.squareup:javapoet:1.13.0' ``` -------------------------------- ### Generating Code Referencing Names with $N in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Illustrates how to use the $N placeholder in JavaPoet to reference other generated declarations, specifically demonstrating how to call one generated MethodSpec (`hexDigit`) from within another (`byteToHex`). ```Java MethodSpec hexDigit = MethodSpec.methodBuilder("hexDigit") .addParameter(int.class, "i") .returns(char.class) .addStatement("return (char) (i < 10 ? i + '0' : i - 10 + 'a')") .build(); MethodSpec byteToHex = MethodSpec.methodBuilder("byteToHex") .addParameter(int.class, "b") .returns(String.class) .addStatement("char[] result = new char[2]") .addStatement("result[0] = $N((b >>> 4) & 0xf)", hexDigit) .addStatement("result[1] = $N(b & 0xf)", hexDigit) .addStatement("return new String(result)") .build(); ``` -------------------------------- ### Generating Dynamic Method with JavaPoet (String Concatenation) (Java) Source: https://github.com/square/javapoet/blob/master/README.md Defines a Java method that uses JavaPoet to build another method dynamically based on input parameters, demonstrating how to incorporate variables into generated code using standard string concatenation. ```Java private MethodSpec computeRange(String name, int from, int to, String op) { return MethodSpec.methodBuilder(name) .returns(int.class) .addStatement("int result = 1") .beginControlFlow("for (int i = " + from + "; i < " + to + "; i++)") .addStatement("result = result " + op + " i") .endControlFlow() .addStatement("return result") .build(); } ``` -------------------------------- ### Generated Method using JavaPoet `addCode` (Java) Source: https://github.com/square/javapoet/blob/master/README.md The resulting Java code generated by the previous JavaPoet snippet using the `addCode` method. Note the manual formatting carried over from the input string. ```Java void main() { int total = 0; for (int i = 0; i < 10; i++) { total += i; } } ``` -------------------------------- ### Adding Annotation with Properties using JavaPoet Java Source: https://github.com/square/javapoet/blob/master/README.md This snippet illustrates how to add an annotation (@Headers) with specific properties (accept, userAgent) using AnnotationSpec.builder. It demonstrates adding members to the annotation specification with string values. ```Java MethodSpec logRecord = MethodSpec.methodBuilder("recordEvent") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addAnnotation(AnnotationSpec.builder(Headers.class) .addMember("accept", "$S", "application/json; charset=utf-8") .addMember("userAgent", "$S", "Square Cash") .build()) .addParameter(LogRecord.class, "logRecord") .returns(LogReceipt.class) .build(); ``` -------------------------------- ### Adding JavaPoet Dependency (Maven XML) Source: https://github.com/square/javapoet/blob/master/README.md Provides the XML snippet required to add the JavaPoet library as a dependency in a Maven project's pom.xml file. ```xml com.squareup javapoet 1.13.0 ``` -------------------------------- ### Creating Abstract Method and Class with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to define an abstract method using `Modifier.ABSTRACT` and add it to an abstract class using JavaPoet. Notes that abstract methods are only valid within abstract classes or interfaces. ```Java MethodSpec flux = MethodSpec.methodBuilder("flux") .addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED) .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addMethod(flux) .build(); ``` ```Java public abstract class HelloWorld { protected abstract void flux(); } ``` -------------------------------- ### Generating Method Returning Date with $T in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Illustrates the use of the `$T` format specifier in JavaPoet to reference existing types like `java.util.Date`. This snippet builds a class with a method that returns a new instance of `Date`, showing how `$T` handles type references and automatic imports. ```java MethodSpec today = MethodSpec.methodBuilder("today") .returns(Date.class) .addStatement("return new $T()", Date.class) .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(today) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); javaFile.writeTo(System.out); ``` -------------------------------- ### Update Maven Dependency for Palantir JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Illustrates the necessary change in Maven or Gradle dependency coordinates when migrating from Square's deprecated JavaPoet to Palantir's maintained fork. ```diff - javapoet = { module = "com.squareup:javapoet", version = "1.13.0" } + javapoet = { module = "com.palantir.javapoet:javapoet", version = "0.5.0" } ``` -------------------------------- ### Generating Methods Returning Strings with $S in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to use the `$S` format specifier in JavaPoet to generate code that includes string literals. This snippet builds a class with multiple methods, each returning a hardcoded string value using `$S` and the `addStatement` method. ```java public static void main(String[] args) throws Exception { TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(whatsMyName("slimShady")) .addMethod(whatsMyName("eminem")) .addMethod(whatsMyName("marshallMathers")) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); javaFile.writeTo(System.out); } private static MethodSpec whatsMyName(String name) { return MethodSpec.methodBuilder(name) .returns(String.class) .addStatement("return $S", name) .build(); } ``` -------------------------------- ### Generated Javadoc Output (Java) Source: https://github.com/square/javapoet/blob/master/README.md Shows the resulting Java code generated by JavaPoet, including the formatted Javadoc comment and the method signature. It illustrates how $T is resolved to the actual type name. ```java /** * Hides {@code message} from the caller's history. Other * participants in the conversation will continue to see the * message in their own history unless they also delete it. * *

Use {@link #delete(Conversation)} to delete the entire * conversation for all participants. */ void dismiss(Message message); ``` -------------------------------- ### Generated Java Method with Annotation Properties Source: https://github.com/square/javapoet/blob/master/README.md This is the Java code generated by the previous JavaPoet snippet. It shows an abstract public method recordEvent annotated with @Headers, where the accept and userAgent properties are correctly set with string values. ```Java @Headers( accept = "application/json; charset=utf-8", userAgent = "Square Cash" ) LogReceipt recordEvent(LogRecord logRecord); ``` -------------------------------- ### Using Named Arguments in JavaPoet CodeBlock (Java) Source: https://github.com/square/javapoet/blob/master/CHANGELOG.md This snippet demonstrates how to use named arguments with CodeBlock.Builder.addNamed() in JavaPoet. It defines a map of arguments and a template string containing placeholders like $count:L, $system:T, and $greeting:S. The addNamed() method substitutes these placeholders with values from the map, allowing for more readable and maintainable code generation templates. ```Java Map map = new LinkedHashMap<>(); map.put("count", 3); map.put("greeting", "Hello, "); map.put("system", System.class); String template = "" + "for (int i = 0; i < $count:L; i++) {\n" + " $system:T.out.println($greeting:S + list.get(i));\n" + "}\n"; CodeBlock.Builder builder = CodeBlock.builder(); builder.addNamed(template, map); ``` -------------------------------- ### Building Fancy Java Enum with Anonymous Classes in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Shows how to create a more complex enum in JavaPoet where constants have custom implementations using `anonymousClassBuilder`, add fields, and define a constructor. ```java TypeSpec helloWorld = TypeSpec.enumBuilder("Roshambo") .addModifiers(Modifier.PUBLIC) .addEnumConstant("ROCK", TypeSpec.anonymousClassBuilder("$S", "fist") .addMethod(MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addStatement("return $S", "avalanche!") .returns(String.class) .build()) .build()) .addEnumConstant("SCISSORS", TypeSpec.anonymousClassBuilder("$S", "peace") .build()) .addEnumConstant("PAPER", TypeSpec.anonymousClassBuilder("$S", "flat") .build()) .addField(String.class, "handsign", Modifier.PRIVATE, Modifier.FINAL) .addMethod(MethodSpec.constructorBuilder() .addParameter(String.class, "handsign") .addStatement("this.$N = $N", "handsign", "handsign") .build()) .build(); ``` ```java public enum Roshambo { ROCK("fist") { @Override public String toString() { return "avalanche!"; } }, SCISSORS("peace"), PAPER("flat"); private final String handsign; Roshambo(String handsign) { this.handsign = handsign; } } ``` -------------------------------- ### Generated Java Method with Override Annotation Source: https://github.com/square/javapoet/blob/master/README.md This is the resulting Java code generated by the preceding JavaPoet snippet. It shows a public method named toString that returns a String and is correctly annotated with @Override. ```Java @Override public String toString() { return "Hoverboard"; } ``` -------------------------------- ### Adding Javadoc with JavaPoet (Java) Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to add Javadoc comments to a MethodSpec using the addJavadoc method in JavaPoet. It shows how to include plain text, newlines, and cross-references using $T for type resolution. ```java MethodSpec dismiss = MethodSpec.methodBuilder("dismiss") .addJavadoc("Hides {@code message} from the caller's history. Other\n" + "participants in the conversation will continue to see the\n" + "message in their own history unless they also delete it.\n") .addJavadoc("\n") .addJavadoc("

Use {@link #delete($T)} to delete the entire\n" + "conversation for all participants.\n", Conversation.class) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addParameter(Message.class, "message") .build(); ``` -------------------------------- ### Building Basic Java Enum with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to use `TypeSpec.enumBuilder` and `addEnumConstant` in JavaPoet to define a simple enum type with public visibility and several constants. ```java TypeSpec helloWorld = TypeSpec.enumBuilder("Roshambo") .addModifiers(Modifier.PUBLIC) .addEnumConstant("ROCK") .addEnumConstant("SCISSORS") .addEnumConstant("PAPER") .build(); ``` ```java public enum Roshambo { ROCK, SCISSORS, PAPER } ``` -------------------------------- ### Generating Method with Custom Type using $T and ClassName in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates using `$T` with `ClassName` to reference types that may not exist at generation time, like a custom `Hoverboard` class. This snippet builds a method returning this custom type, highlighting JavaPoet's ability to handle arbitrary class names and generate corresponding imports. ```java ClassName hoverboard = ClassName.get("com.mattel", "Hoverboard"); MethodSpec today = MethodSpec.methodBuilder("tomorrow") .returns(hoverboard) .addStatement("return new $T()", hoverboard) .build(); ``` -------------------------------- ### Generated Java Method with Nested Annotations Source: https://github.com/square/javapoet/blob/master/README.md This is the final Java code generated by the preceding JavaPoet snippet. It shows the recordEvent method annotated with @HeaderList, which contains an array of @Header annotations, demonstrating nested annotation generation. ```Java @HeaderList({ @Header(name = "Accept", value = "application/json; charset=utf-8"), @Header(name = "User-Agent", value = "Square Cash") }) LogReceipt recordEvent(LogRecord logRecord); ``` -------------------------------- ### Adding Simple Override Annotation with JavaPoet Java Source: https://github.com/square/javapoet/blob/master/README.md This snippet demonstrates how to add a basic @Override annotation to a method using JavaPoet's MethodSpec.methodBuilder and addAnnotation methods. It shows the fluent API for building method specifications including modifiers, return type, and statements. ```Java MethodSpec toString = MethodSpec.methodBuilder("toString") .addAnnotation(Override.class) .returns(String.class) .addModifiers(Modifier.PUBLIC) .addStatement("return $S", "Hoverboard") .build(); ``` -------------------------------- ### Adding Nested Annotations using JavaPoet Java Source: https://github.com/square/javapoet/blob/master/README.md This snippet demonstrates how to create an annotation (@HeaderList) whose properties are themselves annotations (@Header). It uses $L to embed the generated AnnotationSpec for the nested annotations as members of the outer annotation. ```Java MethodSpec logRecord = MethodSpec.methodBuilder("recordEvent") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addAnnotation(AnnotationSpec.builder(HeaderList.class) .addMember("value", "$L", AnnotationSpec.builder(Header.class) .addMember("name", "$S", "Accept") .addMember("value", "$S", "application/json; charset=utf-8") .build()) .addMember("value", "$L", AnnotationSpec.builder(Header.class) .addMember("name", "$S", "User-Agent") .addMember("value", "$S", "Square Cash") .build()) .build()) .addParameter(LogRecord.class, "logRecord") .returns(LogReceipt.class) .build(); ``` -------------------------------- ### Generating Method with Generic Type using $T and ParameterizedTypeName in JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Shows how to use `$T` with `ParameterizedTypeName` to generate code involving generic types, such as `List`. This snippet builds a method that returns a list of custom objects, demonstrating JavaPoet's support for complex type structures and their imports. ```java ClassName hoverboard = ClassName.get("com.mattel", "Hoverboard"); ClassName list = ClassName.get("java.util", "List"); ClassName arrayList = ClassName.get("java.util", "ArrayList"); TypeName listOfHoverboards = ParameterizedTypeName.get(list, hoverboard); MethodSpec beyond = MethodSpec.methodBuilder("beyond") .returns(listOfHoverboards) .addStatement("$T result = new $T<>()", listOfHoverboards, arrayList) .addStatement("result.add(new $T())", hoverboard) .addStatement("result.add(new $T())", hoverboard) .addStatement("result.add(new $T())", hoverboard) .addStatement("return result") .build(); ``` -------------------------------- ### Defining Anonymous Inner Class (Comparator) with JavaPoet Source: https://github.com/square/javapoet/blob/master/README.md Illustrates how to define an anonymous inner class implementing `Comparator` using `TypeSpec.anonymousClassBuilder`, adding a superinterface and overriding the `compare` method. ```java TypeSpec comparator = TypeSpec.anonymousClassBuilder("") .addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class)) .addMethod(MethodSpec.methodBuilder("compare") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(String.class, "a") .addParameter(String.class, "b") .returns(int.class) .addStatement("return $N.length() - $N.length()", "a", "b") .build()) .build(); ``` -------------------------------- ### Using Anonymous Inner Class in JavaPoet Method Statement Source: https://github.com/square/javapoet/blob/master/README.md Demonstrates how to use a previously defined anonymous inner class (`comparator`) as an argument in a method statement within a class builder using the `$L` format specifier. ```java TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addMethod(MethodSpec.methodBuilder("sortByLength") .addParameter(ParameterizedTypeName.get(List.class, String.class), "strings") .addStatement("$T.sort($N, $L)", Collections.class, "strings", comparator) .build()) .build(); ``` ```java void sortByLength(List strings) { Collections.sort(strings, new Comparator() { @Override public int compare(String a, String b) { return a.length() - b.length(); } }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.