1. 程式人生 > >Android自定義processor實現bindView功能

Android自定義processor實現bindView功能

lis dds 定義 java代碼 cli 註冊 文章 type() mage

一、簡介

在現階段的Android開發中,註解越來越流行起來,比如ButterKnife,Retrofit,Dragger,EventBus等等都選擇使用註解來配置。按照處理時期,註解又分為兩種類型,一種是運行時註解,另一種是編譯時註解,運行時註解由於性能問題被一些人所詬病。編譯時註解的核心依賴APT(Annotation Processing Tools)實現,原理是在某些代碼元素上(如類型、函數、字段等)添加註解,在編譯時編譯器會檢查AbstractProcessor的子類,並且調用該類型的process函數,然後將添加了註解的所有元素都傳遞到process函數中,使得開發人員可以在編譯器進行相應的處理,例如,根據註解生成新的Java類,這也就是EventBus,Retrofit,Dragger等開源庫的基本原理。

Java API已經提供了掃描源碼並解析註解的框架,你可以繼承AbstractProcessor類來提供實現自己的解析註解邏輯。下邊我們將學習如何在Android Studio中通過編譯時註解生成java文件。

二、概念

註解處理器是一個在javac中的,用來編譯時掃描和處理的註解的工具。你可以為特定的註解,註冊你自己的註解處理器。
註解處理器可以生成Java代碼,這些生成的Java代碼會組成 .java 文件,但不能修改已經存在的Java類(即不能向已有的類中添加方法)。而這些生成的Java文件,會同時與其他普通的手寫Java源代碼一起被javac編譯。

AbstractProcessor位於javax.annotation.processing包下,我們自己寫processor需要繼承它:

public class LProcessor extends AbstractProcessor
{
    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment)
    {
        super.init(processingEnvironment);
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment)
    {
        return false;
    }

    @Override
    public Set<String> getSupportedAnnotationTypes()
    {
        return super.getSupportedAnnotationTypes();
    }

    @Override
    public SourceVersion getSupportedSourceVersion()
    {
        return super.getSupportedSourceVersion();
    }
}

  

對上面代碼方法簡單講解

  • init(ProcessingEnvironment processingEnvironment): 每一個註解處理器類都必須有一個空的構造函數。然而,這裏有一個特殊的init()方法,它會被註解處理工具調用,並輸入ProcessingEnviroment參數。ProcessingEnviroment提供很多有用的工具類Elements,Types和Filer。後面我們將看到詳細的內容。
  • process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment): 這相當於每個處理器的主函數main()。你在這裏寫你的掃描、評估和處理註解的代碼,以及生成Java文件。輸入參數RoundEnviroment,可以讓你查詢出包含特定註解的被註解元素。後面我們將看到詳細的內容。
  • getSupportedAnnotationTypes(): 這裏你必須指定,這個註解處理器是註冊給哪個註解的。註意,它的返回值是一個字符串的集合,包含本處理器想要處理的註解類型的合法全稱。換句話說,你在這裏定義你的註解處理器註冊到哪些註解上。
  • getSupportedSourceVersion(): 用來指定你使用的Java版本。通常這裏返回SourceVersion.latestSupported()。然而,如果你有足夠的理由只支持Java 7的話,你也可以返回SourceVersion.RELEASE_7。註意:在Java 7以後,你也可以使用註解來代替getSupportedAnnotationTypes()和getSupportedSourceVersion()。

我們先創建一個java module LProcessor

@AutoService(Processor.class)
public class LProcessor extends AbstractProcessor {
    private Elements elementUtils;
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        // 規定需要處理的註解
        return Collections.singleton(LActivity.class.getCanonicalName());
    }
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        System.out.println("DIProcessor");
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(LActivity.class);
        for (Element element : elements) {
            // 判斷是否Class
            TypeElement typeElement = (TypeElement) element;
            List<? extends Element> members = elementUtils.getAllMembers(typeElement);
            MethodSpec.Builder bindViewMethodSpecBuilder = MethodSpec.methodBuilder("bindView")
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(TypeName.VOID)
                    .addParameter(ClassName.get(typeElement.asType()), "activity");
            for (Element item : members) {
                LView diView = item.getAnnotation(LView.class);
                if (diView == null){
                    continue;
                }
                bindViewMethodSpecBuilder.addStatement(String.format("activity.%s = (%s) activity.findViewById(%s)",item.getSimpleName(),ClassName.get(item.asType()).toString(),diView.value()));
            }
            TypeSpec typeSpec = TypeSpec.classBuilder("DI" + element.getSimpleName())
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                    .addMethod(bindViewMethodSpecBuilder.build())
                    .build();
            JavaFile javaFile = JavaFile.builder(getPackageName(typeElement), typeSpec).build();
            try {
                javaFile.writeTo(processingEnv.getFiler());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    private String getPackageName(TypeElement type) {
        return elementUtils.getPackageOf(type).getQualifiedName().toString();
    }
    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        elementUtils = processingEnv.getElementUtils();
    }
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.RELEASE_7;
    }
}
這裏面我們引入了兩個庫
compile ‘com.google.auto.service:auto-service:1.0-rc2‘
compile ‘com.squareup:javapoet:1.7.0‘

 我們再創建一個java module anotation

技術分享圖片

可見,是兩個註解類:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface LActivity {
}

  

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LView {
    int value() default 0;
}

之後我們主工程引入這兩個module 就可以在我們主工程下面用這個註解了,我們make project之後會在工程目錄下build/generated/source/apt下生成對應的java源文件,比如我在下面的activity類使用了定義的註解:

@LActivity
public class TestProcessorActivity extends Activity {
    @LView(R.id.et_input)
    EditText inputView;
    @LView(R.id.button)
    Button buttonView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_processor);
        DITestProcessorActivity.bindView(this);
        buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TestProcessorActivity.this  , inputView.getText().toString() , Toast.LENGTH_SHORT).show();
            }
        });
    }
}

  

則在build/generated/source/apt下生成DITestProcessorActivity.java

public final class DITestProcessorActivity {
  public static void bindView(TestProcessorActivity activity) {
    activity.inputView = (android.widget.EditText) activity.findViewById(2131165237);
    activity.buttonView = (android.widget.Button) activity.findViewById(2131165220);
  }
}
代碼已經自動生成好了,我們就不需要再寫findViewById()了,只需要調用DITestProcessorActivity的bindView方法就可以了。
@LView(R.id.et_input)
EditText inputView;
@LView(R.id.button)
Button buttonView;

  

三、需要了解

我們上面例子主要運用了javapoet和auto-service,具體詳細使用可以參考源碼https://github.com/square/javapoet, 而AutoService比較簡單,就是在使用Java APT的時候,使用AutoService註解,可以自動生成meta信息。網上有很多相關文章,可以好好整理學習下。

Android自定義processor實現bindView功能