【注解】annotationProcessor自动生成代码

2024-09-03 14:58

本文主要是介绍【注解】annotationProcessor自动生成代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用annotationProcessor根据注解自动生成代码。本文先不讲原理,只讲实现过程。尝试了一下在模块化中使用注解自动生成代码,但是会报错:Attribute value must be constant。这是因为在library模块中使用该注解(即使用BindView绑定id)
image.png
而library构建时产生的R文件在壳模块app中,如下图所示:
image.png
所以在library中使用注解绑定id,该id就不是常量类型,因此会报错,目前不知道该如何解决,希望有大佬指点一二。

1 创建项目

  • 项目结构
    项目结构

annotation:注解类的java-library
app:主工程
compiler:主要用于根据注解类来生成对应代码的java-library

  • 创建annotation的java-library

image.png

BindView.java

package com.example.annotation;import androidx.annotation.IdRes;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface BindView {@IdRes int value();
}

OnClick.java

package com.example.annotation;import androidx.annotation.IdRes;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Created by yds* on 2020/3/6.*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface OnClick {@IdRes int value();
}

Keep.java

package com.example.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Created by yds* on 2020/3/6.*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface Keep {
}

BindingSuffix.java

package com.example.annotation;
/*** Created by yds* on 2020/3/6.*/
public class BindingSuffix {public static final String GENERATED_CLASS_SUFFIX = "$Binding";private BindingSuffix() {}
}

build.gradle

apply plugin: 'java-library'dependencies {implementation fileTree(dir: 'libs', include: ['*.jar'])implementation 'androidx.annotation:annotation:1.1.0'}sourceCompatibility = "1.8"
targetCompatibility = "1.8"
  • 创建compiler库
    compiler也是java-library类型的module

MyProcessor.java

package com.example.compiler;import com.example.annotation.BindView;
import com.example.annotation.Keep;
import com.example.annotation.OnClick;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;@AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {private Filer filer;private Messager messager;private Elements elementUtils;//每个存在注解的类整理出来,key:package_classname value:被注解的类型元素private Map<String, List<Element>> annotationClassMap = new HashMap<>();@Overridepublic synchronized void init(ProcessingEnvironment processingEnv) {super.init(processingEnv);filer = processingEnv.getFiler();messager = processingEnv.getMessager();elementUtils = processingEnv.getElementUtils();}@Overridepublic boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {if (!roundEnv.processingOver()) {buildAnnotatedElement(roundEnv, BindView.class);buildAnnotatedElement(roundEnv, OnClick.class);}else {for (Map.Entry<String, List<Element>> entry : annotationClassMap.entrySet()) {String packageName = entry.getKey().split("_")[0];String typeName = entry.getKey().split("_")[1];ClassName className = ClassName.get(packageName, typeName);ClassName generatedClassName = ClassName.get(packageName, NameStore.getGeneratedClassName(typeName));/*创建要生成的类,如下所示@Keeppublic class MainActivity$Binding {}*/TypeSpec.Builder classBuilder = TypeSpec.classBuilder(generatedClassName).addModifiers(Modifier.PUBLIC).addAnnotation(Keep.class);/*添加构造函数*   public MainActivity$Binding(MainActivity activity) {bindViews(activity);bindOnClicks(activity);}*/classBuilder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(className, NameStore.Variable.ANDROID_ACTIVITY).addStatement("$N($N)",NameStore.Method.BIND_VIEWS,NameStore.Variable.ANDROID_ACTIVITY).addStatement("$N($N)",NameStore.Method.BIND_ON_CLICKS,NameStore.Variable.ANDROID_ACTIVITY).build());/*创建方法bindViews(MainActivity activity)* private void bindViews(MainActivity activity) {}*/MethodSpec.Builder bindViewsMethodBuilder = MethodSpec.methodBuilder(NameStore.Method.BIND_VIEWS).addModifiers(Modifier.PRIVATE).returns(void.class).addParameter(className, NameStore.Variable.ANDROID_ACTIVITY);/*增加方法体* activity.tvHello = (TextView)activity.findViewById(2131165326);* */for (VariableElement variableElement : ElementFilter.fieldsIn(entry.getValue())) {BindView bindView = variableElement.getAnnotation(BindView.class);if (bindView != null) {bindViewsMethodBuilder.addStatement("$N.$N = ($T)$N.findViewById($L)",NameStore.Variable.ANDROID_ACTIVITY,variableElement.getSimpleName(),variableElement,NameStore.Variable.ANDROID_ACTIVITY,bindView.value());}}//将构建出来的方法添加到类里面classBuilder.addMethod(bindViewsMethodBuilder.build());/*以下构建如下代码*   private void bindOnClicks(final MainActivity activity) {activity.findViewById(2131165218).setOnClickListener(new View.OnClickListener() {public void onClick(View view) {activity.onHelloBtnClick(view);}});}*/ClassName androidOnClickListenerClassName = ClassName.get(NameStore.Package.ANDROID_VIEW,NameStore.Class.ANDROID_VIEW,NameStore.Class.ANDROID_VIEW_ON_CLICK_LISTENER);ClassName androidViewClassName = ClassName.get(NameStore.Package.ANDROID_VIEW,NameStore.Class.ANDROID_VIEW);MethodSpec.Builder bindOnClicksMethodBuilder = MethodSpec.methodBuilder(NameStore.Method.BIND_ON_CLICKS).addModifiers(Modifier.PRIVATE).returns(void.class).addParameter(className, NameStore.Variable.ANDROID_ACTIVITY, Modifier.FINAL);for (ExecutableElement executableElement : ElementFilter.methodsIn(entry.getValue())) {OnClick onClick = executableElement.getAnnotation(OnClick.class);if (onClick != null) {TypeSpec onClickListenerClass = TypeSpec.anonymousClassBuilder("").addSuperinterface(androidOnClickListenerClassName).addMethod(MethodSpec.methodBuilder(NameStore.Method.ANDROID_VIEW_ON_CLICK).addModifiers(Modifier.PUBLIC).addParameter(androidViewClassName, NameStore.Variable.ANDROID_VIEW).addStatement("$N.$N($N)",NameStore.Variable.ANDROID_ACTIVITY,executableElement.getSimpleName(),NameStore.Variable.ANDROID_VIEW).returns(void.class).build()).build();bindOnClicksMethodBuilder.addStatement("$N.findViewById($L).setOnClickListener($L)",NameStore.Variable.ANDROID_ACTIVITY,onClick.value(),onClickListenerClass);}}classBuilder.addMethod(bindOnClicksMethodBuilder.build());//将类写入文件中try {JavaFile.builder(packageName,classBuilder.build()).build().writeTo(filer);} catch (IOException e) {messager.printMessage(Diagnostic.Kind.ERROR, e.toString());}}}return true;}@Overridepublic Set<String> getSupportedAnnotationTypes() {return new TreeSet<>(Arrays.asList(BindView.class.getCanonicalName(),OnClick.class.getCanonicalName(),Keep.class.getCanonicalName()));}@Overridepublic SourceVersion getSupportedSourceVersion() {return SourceVersion.latestSupported();}private void buildAnnotatedElement(RoundEnvironment roundEnv, Class<? extends Annotation> clazz) {for (Element element : roundEnv.getElementsAnnotatedWith(clazz)) {String className = getFullClassName(element);List<Element> cacheElements = annotationClassMap.get(className);if (cacheElements == null) {cacheElements = new ArrayList<>();annotationClassMap.put(className, cacheElements);}cacheElements.add(element);}}private String getFullClassName(Element element) {TypeElement typeElement = (TypeElement) element.getEnclosingElement();String packageName = elementUtils.getPackageOf(typeElement).getQualifiedName().toString();return packageName + "_" + typeElement.getSimpleName().toString();}
}

这里的类上面一定要加上@AutoService(Processor.class),如果不加上,你必须在main目录下面创建一个resources/META-INF/services/javax.annotation.processing.Processor,并在该文件里加入你所编写的Processor类,如下图所示:
image.png
否则,将不会自动生成类。

NameStore.java

package com.example.compiler;import com.example.annotation.BindingSuffix;/*** Created by yds* on 2020/3/5.*/
public final class NameStore {private NameStore(){}public static String getGeneratedClassName(String clsName){return clsName+ BindingSuffix.GENERATED_CLASS_SUFFIX;}public static class Package{public static final String ANDROID_VIEW = "android.view";}public static class Class {// Androidpublic static final String ANDROID_VIEW = "View";public static final String ANDROID_VIEW_ON_CLICK_LISTENER = "OnClickListener";}public static class Variable{public static final String ANDROID_ACTIVITY = "activity";public static final String ANDROID_VIEW = "view";}public static class Method{public static final String ANDROID_VIEW_ON_CLICK = "onClick";// Binderpublic static final String BIND_VIEWS = "bindViews";public static final String BIND_ON_CLICKS = "bindOnClicks";public static final String BIND = "bind";}
}

build.gradle

apply plugin: 'java-library'dependencies {implementation fileTree(dir: 'libs', include: ['*.jar'])implementation 'com.squareup:javapoet:1.11.1'implementation project(path:':annotation')implementation 'com.google.auto.service:auto-service:1.0-rc5'annotationProcessor 'com.google.auto.service:auto-service:1.0-rc5'
}sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
  • app中类的编写
    Binding.java
package com.example.binder;import android.app.Activity;import com.example.annotation.BindingSuffix;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;/*** Created by yds* on 2020/3/6.*/
public class Binding {private Binding(){}private static <T extends Activity> void instantiateBinder(T target, String suffix){Class<?> targetClass=target.getClass();String className=targetClass.getName();try {Class<?>bindingClass =targetClass.getClassLoader().loadClass(className+suffix);Constructor<?> classConstructor=bindingClass.getConstructor(targetClass);try {classConstructor.newInstance(target);} catch (IllegalAccessException e) {throw new RuntimeException("Unable to invoke " + classConstructor, e);} catch (InstantiationException e) {throw new RuntimeException("Unable to invoke " + classConstructor, e);} catch (InvocationTargetException e) {Throwable cause = e.getCause();if (cause instanceof RuntimeException) {throw (RuntimeException) cause;}if (cause instanceof Error) {throw (Error) cause;}throw new RuntimeException("Unable to create instance.", cause);}} catch (ClassNotFoundException e) {throw new RuntimeException("Unable to find Class for " + className + suffix, e);} catch (NoSuchMethodException e) {throw new RuntimeException("Unable to find constructor for " + className + suffix, e);}}public static <T extends Activity> void bind(T activity) {instantiateBinder(activity, BindingSuffix.GENERATED_CLASS_SUFFIX);}
}

MainActivity.java

package com.example.annotationdemo6;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;import com.example.annotation.BindView;
import com.example.annotation.OnClick;
import com.example.binder.Binding;public class MainActivity extends AppCompatActivity {@BindView(R.id.tv)TextView mTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Binding.bind(this);mTextView.setText("Hello world");}@OnClick(R.id.btn)void clickByBtn(View v){Intent intent = new Intent();intent.setClass(MainActivity.this,JumpActivity.class);startActivity(intent);}
}

build.gradle

apply plugin: 'com.android.application'android {compileSdkVersion 29buildToolsVersion "29.0.0"defaultConfig {applicationId "com.example.annotationdemo6"minSdkVersion 21targetSdkVersion 29versionCode 1versionName "1.0"testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}
}dependencies {implementation fileTree(dir: 'libs', include: ['*.jar'])implementation project(':annotation')annotationProcessor project(':compiler')implementation 'androidx.appcompat:appcompat:1.1.0'implementation 'androidx.constraintlayout:constraintlayout:1.1.3'testImplementation 'junit:junit:4.12'androidTestImplementation 'androidx.test:runner:1.2.0'androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

源码:https://github.com/Yedongsheng/AnnotationDemo2

这篇关于【注解】annotationProcessor自动生成代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1133286

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

java之Objects.nonNull用法代码解读

《java之Objects.nonNull用法代码解读》:本文主要介绍java之Objects.nonNull用法代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录Java之Objects.nonwww.chinasem.cnNull用法代码Objects.nonN

java中使用POI生成Excel并导出过程

《java中使用POI生成Excel并导出过程》:本文主要介绍java中使用POI生成Excel并导出过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求说明及实现方式需求完成通用代码版本1版本2结果展示type参数为atype参数为b总结注:本文章中代码均为