千家信息网

Android中如何通过自定义processor实现bindView功能

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,本篇内容主要讲解"Android中如何通过自定义processor实现bindView功能",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Android中如
千家信息网最后更新 2025年02月05日Android中如何通过自定义processor实现bindView功能

本篇内容主要讲解"Android中如何通过自定义processor实现bindView功能",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Android中如何通过自定义processor实现bindView功能"吧!

一、简介

在现阶段的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 set, RoundEnvironment roundEnvironment) { return false; }  @Override public Set getSupportedAnnotationTypes() { return super.getSupportedAnnotationTypes(); }  @Override public SourceVersion getSupportedSourceVersion() { return super.getSupportedSourceVersion(); }}

对上面代码方法简单讲解

init(ProcessingEnvironment processingEnvironment): 每一个注解处理器类都必须有一个空的构造函数。然而,这里有一个特殊的init()方法,它会被注解处理工具调用,并输入ProcessingEnviroment参数。ProcessingEnviroment提供很多有用的工具类Elements,Types和Filer。后面我们将看到详细的内容。

process(Set 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 getSupportedAnnotationTypes() {  // 规定需要处理的注解  return Collections.singleton(LActivity.class.getCanonicalName()); } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) {  System.out.println("DIProcessor");  Set elements = roundEnv.getElementsAnnotatedWith(LActivity.class);  for (Element element : elements) {   // 判断是否Class   TypeElement typeElement = (TypeElement) element;   List 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类使用了定义的注解:

@LActivitypublic 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()了:@LView(R.id.et_input)EditText inputView;@LView(R.id.button)Button buttonView;

到此,相信大家对"Android中如何通过自定义processor实现bindView功能"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0