Android自定義processor實現bindView功能

1、簡介

在現階段的Android開發中,註解愈來愈流行起來,好比ButterKnife,Retrofit,Dragger,EventBus等等都選擇使用註解來配置。按照處理時期,註解又分爲兩種類型,一種是運行時註解,另外一種是編譯時註解,運行時註解因爲性能問題被一些人所詬病。編譯時註解的核心依賴APT(Annotation Processing Tools)實現,原理是在某些代碼元素上(如類型、函數、字段等)添加註解,在編譯時編譯器會檢查AbstractProcessor的子類,而且調用該類型的process函數,而後將添加了註解的全部元素都傳遞到process函數中,使得開發人員能夠在編譯器進行相應的處理,例如,根據註解生成新的Java類,這也就是EventBus,Retrofit,Dragger等開源庫的基本原理。 
Java API已經提供了掃描源碼並解析註解的框架,你能夠繼承AbstractProcessor類來提供實現本身的解析註解邏輯。下邊咱們將學習如何在Android Studio中經過編譯時註解生成java文件。java

2、概念

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

AbstractProcessor位於javax.annotation.processing包下,咱們本身寫processor須要繼承它:android

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();
    }
}

  

對上面代碼方法簡單講解git

  • 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 LProcessorgithub

@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框架

可見,是兩個註解類:ide

@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;

  

3、須要瞭解

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

相關文章
相關標籤/搜索