创建一个我们自己的注解处理器

2020-04-18  本文已影响0人  kunio

自定义一个注解处理器可以按照如下步骤进行:
1.

创建一个java library(注意不要创建Android library),我们定义名称为kunio-annotation,如下所示:
注解工程.png

其中build.gradle文件如下:

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

}

sourceCompatibility = "8"
targetCompatibility = "8"

在工程下新建一个我们自定义的注解:

package com.kunio.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface Kunio {
    String value() default "";
}

2.

创建我们自己的注解处理器module(同样也是java library),命名为kunio-processor,如下所示:
注解处理器.png

build.gradle文件如下:

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':kunio-annotation')
    implementation 'com.google.auto.service:auto-service:1.0-rc2'
//    implementation 'com.squareup:javapoet:1.7.0'
    // gradle大于5之后需要自己加上以下代码,我自己现在的版本是5.4.1
   // distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
    annotationProcessor 'com.google.auto.service:auto-service:1.0-rc2'
}
// 当前的版本与annotation的版本保持一致
sourceCompatibility = "8"
targetCompatibility = "8"

然后我们创建自定义的Processor

package com.kunio.processor;

import com.google.auto.service.AutoService;
import com.kunio.annotation.Kunio;

import java.util.Collections;
import java.util.Set;
import java.util.logging.Logger;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;

@AutoService(Processor.class)
//@SupportedAnnotationTypes({"com.kunio.annotation.Kunio"})
//@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class KunioProcessor extends AbstractProcessor {

    private Messager messager;

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        messager.printMessage(Diagnostic.Kind.NOTE, "startProcessor----kunio");
        return true;
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        // 也可以在;类上加上该注解,注解内定义当前版本
        // @SupportedSourceVersion(SourceVersion.RELEASE_8)
        return SourceVersion.latestSupported();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        // 也可以在类上加上该注解,注解内定义当前支持的我们自定义注解的路径
        // @SupportedAnnotationTypes({"com.kunio.annotation.Kunio"})
        return Collections.singleton(Kunio.class.getCanonicalName());
    }

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        messager = processingEnvironment.getMessager();
    }
}

现在我们已经定义好了我们的注解与注解处理器,现在需要在我们的工程里面去使用它;
新建一个Android module,命名为sample:


工程.png

build.gradle如下所示:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.kunio.sample"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //  我们在这里面依赖了之前定义好的annotation和processor
    annotationProcessor  project(path: ':kunio-processor')
    implementation project(path: ':kunio-annotation')
}

新建一个类使用我们的自定义注解:

package com.kunio.sample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.kunio.annotation.Kunio;

@Kunio
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

然后我们点击Build->Rebuild Project,之后我们就可以在task中看到我们的输出日志了:

> Task :sample:mergeDebugAssets
> Task :sample:mergeDebugResources
> Task :sample:processDebugResources

> Task :sample:compileDebugJavaWithJavac
Gradle may disable incremental compilation as the following annotation processors are not incremental: kunio-processor.jar (project :kunio-processor), auto-service-1.0-rc2.jar (com.google.auto.service:auto-service:1.0-rc2).
Consider setting the experimental feature flag android.enableSeparateAnnotationProcessing=true in the gradle.properties file to run annotation processing in a separate task and make compilation incremental.
// 这里就是我们的输出日志,对应于KunioProcessor的process方法中的实现
ע: startProcessor----kunio
ע: startProcessor----kunio

> Task :sample:compileDebugSources
> Task :sample:processDebugJavaRes NO-SOURCE
> Task :sample:transformClassesWithDexBuilderForDebug

好了,最基本的方式我们已经知道怎么去定义一个自己的注解处理器了,一些比较复杂的也是基于这些方式,只是在process方法中具体的实现逻辑不一样。

上一篇 下一篇

猜你喜欢

热点阅读