深入Dagger:JavaPoet的使用


前言

最近在用Dagger開發應用,Dagger是google在square的基礎上去反射的依賴注入框架。 Dagger會根據定義的注解在編譯階段根據依賴注入的配置生成相應的代碼,來減少運行期間反射的開銷。 Dagger依賴了JavaPoet和JavaFormat來輔助實現生成代碼,這里主要介紹下JavaPoet的內容和使用。

JavaPoet

JavaPoet這樣定義自己的項目。

Use beautiful Java code to generate beautiful Java code

所以JavaPoet定義了一系列類來盡可能優雅的描述java源文件的結構。觀察JavaPoet的代碼主要的類可以分為以下幾種:

  • Spec 用來描述Java中基本的元素,包括類型,注解,字段,方法和參數等。
    • AnnotationSpec
    • FieldSpec
    • MethodSpec
    • ParameterSpec
    • TypeSpec
  • Name 用來描述類型的引用,包括Void,原始類型(int,long等)和Java類等。
    • TypeName
    • ArrayTypeName
    • ClassName
    • ParameterizedTypeName
    • TypeVariableName
    • WildcardTypeName
  • CodeBlock 用來描述代碼塊的內容,包括普通的賦值,if判斷,循環判斷等。
  • JavaFile 完整的Java文件,JavaPoet的主要的入口。
  • CodeWriter 讀取JavaFile並轉換成可閱讀可編譯的Java源文件。

示例

下面通過一個例子來完整的實現一個Java類的定義。 通過下面的maven依賴可以引用JavaPoet包。

    <dependency>
        <groupId>com.squareup</groupId>
        <artifactId>javapoet</artifactId>
        <version>1.7.0</version>
    </dependency>

完整的代碼放在Github。這里介紹一下主要的方法。

  1. AnnotationSpec 添加MyAnnotation的注解,然后設置屬性hello=world
    private static AnnotationSpec makeAnnotationSpec() {
        AnnotationSpec.Builder builder = AnnotationSpec.builder(ClassName.get("org.wcong.test.poet", "MyAnnotation"));
        CodeBlock.Builder codeBlockBuilder = CodeBlock.builder().add("$S", "world");
        builder.addMember("hello", codeBlockBuilder.build());
        return builder.build();
    }
  1. FieldSpec 創建hello的字段並初始化為“world”。
    private static FieldSpec makeFieldSpec() {
		FieldSpec.Builder fileSpecBuilder = FieldSpec.builder(String.class, "hello", Modifier.PRIVATE);
		fileSpecBuilder.initializer(CodeBlock.of("\"world\""));
		return fileSpecBuilder.build();
	}
  1. MethodSpec 創建getHello,setHello,toString方法。 toString使用了ControlFlow判斷了hello不等於null,返回"hello world",等於null的時候返回空。
    private static MethodSpec makeToStringMethod() {
		MethodSpec.Builder toStringBuilder = MethodSpec.methodBuilder("toString");
		toStringBuilder.addModifiers(Modifier.PUBLIC);
		toStringBuilder.returns(TypeName.get(String.class));
		CodeBlock.Builder toStringCodeBuilder = CodeBlock.builder();
        toStringCodeBuilder.beginControlFlow("if( hello != null )");
        toStringCodeBuilder.add(CodeBlock.of("return \"hello \"+hello;\n"));
        toStringCodeBuilder.nextControlFlow("else");
        toStringCodeBuilder.add(CodeBlock.of("return \"\";\n"));
		toStringCodeBuilder.endControlFlow();
		toStringBuilder.addCode(toStringCodeBuilder.build());
		return toStringBuilder.build();
	}
    private static MethodSpec makeSetMethod() {
		MethodSpec.Builder setMethodSpecBuilder = MethodSpec.methodBuilder("setHello");
		setMethodSpecBuilder.addModifiers(Modifier.PUBLIC);
		setMethodSpecBuilder.returns(TypeName.VOID);
		ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(TypeName.get(String.class), "hello");
		setMethodSpecBuilder.addParameter(parameterBuilder.build());
		setMethodSpecBuilder.addCode(CodeBlock.builder().add("this.hello = hello;\n").build());
		return setMethodSpecBuilder.build();
	}
	private static MethodSpec makeGetMethod() {
		MethodSpec.Builder getMethodSpecBuilder = MethodSpec.methodBuilder("getHello");
		getMethodSpecBuilder.addModifiers(Modifier.PUBLIC);
		getMethodSpecBuilder.returns(TypeName.get(String.class));
		getMethodSpecBuilder.addCode(CodeBlock.builder().add("return hello;\n").build());
		return getMethodSpecBuilder.build();
	}
  1. JavaFile JavaPoet的主入口,用來描述Java源文件。
    public static void main(String[] args) {
		TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder("JavaFile");
		typeSpecBuilder.addAnnotation(makeAnnotationSpec());
		typeSpecBuilder.addField(makeFieldSpec());
		typeSpecBuilder.addMethods(makeMethodSpec());
		JavaFile.Builder javaFileBuilder = JavaFile.builder("org.wcong.test.poet", typeSpecBuilder.build());
		System.out.println(javaFileBuilder.build().toString());
	}

運行后輸出下面的信息,就是一個完整的類文件了

package org.wcong.test.poet;

import java.lang.String;

@MyAnnotation(
    hello = "world"
)
class JavaFile {
  private String hello = "world";

  public String getHello() {
    return hello;
  }

  public void setHello(String hello) {
    this.hello = hello;
  }

  public String toString() {
    if( hello != null ) {
      return "hello "+hello;
    } else {
      return "";
    }
  }
}

結語

dagger使用JavaPoet來保存自動生成的類的信息,並通過JavaFormat來格式化生成的Java源文件。后面會介紹關於JavaFormat的內容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM