JavaPoet Documentation

repository·master·Indexed 27 days ago

https://github.com/square/javapoet

A Java API for generating .java source files, designed to eliminate boilerplate for annotation processing and metadata interaction. It uses a builder pattern with TypeSpec, MethodSpec, and JavaFile to construct code models, featuring format specifiers ($L, $S, $T, $N) for safe code injection and control flow management. Note: This project was deprecated as of 2020-10-10; users are encouraged to migrate to Palantir's JavaPoet.

Tokens
2K
Snippets
7
Records
13
Agent score
45%

What's inside JavaPoet

  1. Set up the mvn-release alias

    master

    For a streamlined release process, add the following alias to your shell's .rc file (e.g., .bashrc or .zshrc). This command performs a clean build, verifies the project, cleans the release environment, prepares the release, and performs the release.

    alias mvn-release='mvn clean source:jar javadoc:jar verify && mvn clean release:clean && mvn release:prepare release:perform'
  2. Install JavaPoet via Maven or Gradle

    master

    To use JavaPoet in your project, add the following dependency to your build configuration. Note that this project is deprecated as of 2020-10-10; for modern Java features, consider using Palantir's JavaPoet.

    <!-- Maven -->
    <dependency>
      <groupId>com.squareup</groupId>
      <artifactId>javapoet</artifactId>
      <version>1.13.0</version>
    </dependency>
    
    <!-- Gradle -->
    compile 'com.squareup:javapoet:1.13.0'
  3. Configure Maven settings for Sonatype Nexus

    master

    To release artifacts to Sonatype Nexus, you must configure your ~/.m2/settings.xml file with a server entry containing the sonatype-nexus-staging ID and your credentials.

    <settings>
      <servers>
        <server>
          <id>sonatype-nexus-staging</id>
          <username>your-nexus-username</username>
          <password>your-nexus-password</password>
        </server>
      </servers>
    </settings>
  4. Release a new version of JavaPoet

    master

    Follow these steps to perform a release:

    1. Update CHANGELOG.md for the impending release.
    2. Update README.md with the new version.
    3. Commit the changes: git commit -am "Update changelog for X.Y.Z." (replace X.Y.Z with the new version).
    4. Run the mvn-release command and follow the prompts:
      • Release version: Hit Enter to accept the default.
      • SCM release tag: Hit Enter to accept the default.
      • New development version: Enter the next snapshot version (e.g., X.(Y + 1).0-SNAPSHOT).
      • Provide your GPG Passphrase when prompted.
    5. Visit Sonatype Nexus and promote the artifact.

    Troubleshooting Release Failures: If step 4 or 5 fails:

    1. Drop the Sonatype repo.
    2. Fix the issue.
    3. Manually revert the version change in pom.xml made by mvn-release.
    4. Commit the revert.
    5. Restart the process from step 4.
    git commit -am "Update changelog for X.Y.Z."
    mvn-release
  5. Migrate from Square JavaPoet to Palantir JavaPoet

    master

    Since Square's JavaPoet is deprecated, you may want to migrate to Palantir's version.

    1. Update Maven coordinates:

      • From: com.squareup:javapoet:1.13.0
      • To: com.palantir.javapoet:javapoet:0.5.0
    2. Update Imports: Use sed to replace com.squareup.javapoet with com.palantir.javapoet in your source files.

    3. Update API usage: Some fields in the Square version have become methods in the Palantir version (e.g., javaFile.packageName becomes javaFile.packageName()).

  6. Generate a basic Java class with JavaPoet

    master

    JavaPoet uses a builder pattern to construct code models. You define MethodSpec for methods, TypeSpec for classes/interfaces/enums, and JavaFile to wrap them into a complete file. You can write the output to System.out, a String, or directly to the file system.

    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);
  7. Create Enums and Interfaces

    master
    Use TypeSpec.enumBuilder(String) to create enums and addEnumConstant(String) for values. For interfaces, use TypeSpec.interfaceBuilder(String). Note that JavaPoet automatically handles default modifiers for interfaces (e.g., PUBLIC_ABSTRACT for methods) to ensure valid generated code.
  8. Use format specifiers in code blocks

    master

    JavaPoet uses special placeholders in strings to safely inject code elements. This prevents manual string concatenation and handles escaping/imports automatically.

    • $L (Literals): Emits a literal value (strings, primitives, etc.) directly without escaping.
    • $S (Strings): Emits a string literal, automatically adding surrounding quotation marks and escaping internal characters.
    • $T (Types): Emits a type and automatically manages the necessary import statements. You can pass a Class object or a TypeName (like ClassName or ParameterizedTypeName).
    • $N (Names): Refers to the name of another generated declaration (e.g., a MethodSpec or FieldSpec) to ensure self-referential code is correct.
  9. Add Annotations to code

    master

    Use AnnotationSpec.builder(Class) to define an annotation. You can add members using .addMember(String name, String format, Object... args). To nest annotations, use $L with another AnnotationSpec.

    MethodSpec logRecord = MethodSpec.methodBuilder("recordEvent")
        .addAnnotation(AnnotationSpec.builder(Headers.class)
            .addMember("accept", "$S", "application/json; charset=utf-8")
            .build())
        .build();
  10. Define Methods and Constructors

    master
    Use MethodSpec.methodBuilder(String) to create methods. Use MethodSpec.constructorBuilder() to create constructors. Both support modifiers (via Modifier), return types, parameters, and code statements. For abstract methods, use Modifier.ABSTRACT.
  11. Define Fields and Parameters

    master
    Fields can be created using FieldSpec.builder(Class, String, Modifier...) or by adding them to a TypeSpec.Builder via .addField(). Parameters can be defined using ParameterSpec.builder(Class, String, Modifier...) or via MethodSpec.Builder.addParameter().