自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

注解APT應(yīng)用詳解(手把手教你寫B(tài)utterKnife工具)

移動(dòng)開發(fā) Android
APT(Annotation Processing Tool)即注解處理器,是一種處理注解的工具,確切的說它是javac的一個(gè)工具,它用來在編譯時(shí)掃描和處理注解。注解處理器以Java代碼(或者編譯過的字節(jié)碼)作為輸入,生成.java文件作為輸出。

 [[410458]]

本文轉(zhuǎn)載自微信公眾號(hào)「Android開發(fā)編程」,作者Android開發(fā)編程。轉(zhuǎn)載本文請(qǐng)聯(lián)系A(chǔ)ndroid開發(fā)編程公眾號(hào)。

一、APT是什么?有什么用,帶著疑惑來學(xué)習(xí)

  • APT(Annotation Processing Tool)即注解處理器,是一種處理注解的工具,確切的說它是javac的一個(gè)工具,它用來在編譯時(shí)掃描和處理注解。注解處理器以Java代碼(或者編譯過的字節(jié)碼)作為輸入,生成.java文件作為輸出;
  • 簡單來說就是在編譯期,通過注解生成.java文件;
  • 使用APT的優(yōu)點(diǎn)就是方便、簡單,可以少些很多重復(fù)的代碼;用過ButterKnife、Dagger、EventBus等注解框架的同學(xué)就能感受到,利用這些框架可以少些很多代碼,只要寫一些注解就可以了,他們不過是通過注解,幫助生成了一些高效代碼;

二、APT應(yīng)用-仿照ButterKnife寫個(gè)注解

通過APT實(shí)現(xiàn)一個(gè)功能,通過對(duì)View變量的注解,實(shí)現(xiàn)View的綁定

1、創(chuàng)建幾個(gè)Library來聲明

  1. Android Library:aptlibs 正常的寫Android的lib   
  2. Java or Kotlin Library:aptlib-anno (專門放我們編寫的注解) 
  3. Java or Kotlin Library :aptlib-processor (編寫動(dòng)態(tài)生成文件的邏輯) 
  4. aptlibs 
  5. plugins { 
  6.     id 'com.android.library' 
  7.     id 'kotlin-android' 
  8. aptlib-anno  
  9. plugins { 
  10.     id 'java-library' 
  11. aptlib-processor 
  12. 是plugins { 
  13.     id 'java-library' 

這個(gè)要記清楚,很多博主估計(jì)自己都沒有寫過apt,分不清楚AndroidLib和javaLib

apt 本來java 提供的,另外 Android庫中不允許繼承AbstractProcessor

2 、定義注解-自定義注解

記住要在 aptlib-anno 庫下面創(chuàng)建

  1. @Retention(RetentionPolicy.CLASS) 
  2. @Target(ElementType.FIELD) 
  3. public @interface BindView { 
  4.     int value(); 

定義了運(yùn)行時(shí)注解BindView,其中value()用于獲取對(duì)應(yīng)View的id;

  • @Retention(RetentionPolicy.CLASS):表示編譯時(shí)注解
  • @Target(ElementType.FIELD):表示注解范圍為類成員(構(gòu)造方法、方法、成員變量)
  • @Retention:定義被保留的時(shí)間長短
  • RetentionPoicy.SOURCE、RetentionPoicy.CLASS、RetentionPoicy.RUNTIME
  • @Target:定義所修飾的對(duì)象范圍
  • TYPE、FIELD、METHOD、PARAMETER、CONSTRUCTOR、LOCAL_VARIABLE等

3、定義注解處理器-動(dòng)態(tài)生成關(guān)聯(lián)文件

aptlib-processor 庫

首先在本lib下添加依賴

  1. dependencies { 
  2.     implementation 'com.google.auto.service:auto-service:1.0-rc2'  
  3.     implementation project(':aptlib-anno'

創(chuàng)建BindViewProcessor

  1. @AutoService(Processor.class) 
  2. public class BindViewProcessor extends AbstractProcessor { 
  3.     private Messager mMessager; 
  4.     private Elements mElementUtils; 
  5.     private Map<String, ClassCreatorProxy> mProxyMap = new HashMap<>(); 
  6.     @Override 
  7.     public synchronized void init(ProcessingEnvironment processingEnv) { 
  8.         super.init(processingEnv); 
  9.         mMessager = processingEnv.getMessager(); 
  10.         mElementUtils = processingEnv.getElementUtils(); 
  11.     } 
  12.     @Override 
  13.     public Set<String> getSupportedAnnotationTypes() { 
  14.         HashSet<String> supportTypes = new LinkedHashSet<>(); 
  15.         supportTypes.add(BindView.class.getCanonicalName()); 
  16.         return supportTypes; 
  17.     } 
  18.     @Override 
  19.     public SourceVersion getSupportedSourceVersion() { 
  20.         return SourceVersion.latestSupported(); 
  21.     } 
  22.     @Override 
  23.     public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnv) { 
  24.            mMessager.printMessage(Diagnostic.Kind.NOTE, "processing..."); 
  25.         mProxyMap.clear(); 
  26.         //得到所有的注解 
  27.         Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class); 
  28.         for (Element element : elements) { 
  29.             VariableElement variableElement = (VariableElement) element; 
  30.             TypeElement classElement = (TypeElement) variableElement.getEnclosingElement(); 
  31.             String fullClassName = classElement.getQualifiedName().toString(); 
  32.             ClassCreatorProxy proxy = mProxyMap.get(fullClassName); 
  33.             if (proxy == null) { 
  34.                 proxy = new ClassCreatorProxy(mElementUtils, classElement); 
  35.                 mProxyMap.put(fullClassName, proxy); 
  36.             } 
  37.             BindView bindAnnotation = variableElement.getAnnotation(BindView.class); 
  38.             int id = bindAnnotation.value(); 
  39.             proxy.putElement(id, variableElement); 
  40.         } 
  41.         //通過遍歷mProxyMap,創(chuàng)建java文件 
  42.         for (String key : mProxyMap.keySet()) { 
  43.             ClassCreatorProxy proxyInfo = mProxyMap.get(key); 
  44.             try { 
  45.                 mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName()); 
  46.                 JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(), proxyInfo.getTypeElement()); 
  47.                 Writer writer = jfo.openWriter(); 
  48.                 writer.write(proxyInfo.generateJavaCode()); 
  49.                 writer.flush(); 
  50.                 writer.close(); 
  51.             } catch (IOException e) { 
  52.                 mMessager.printMessage(Diagnostic.Kind.NOTE, " --> create " + proxyInfo.getProxyClassFullName() + "error"); 
  53.             } 
  54.         } 
  55.         mMessager.printMessage(Diagnostic.Kind.NOTE, "process finish ..."); 
  56.         return true
  57.     } 
  1. public class ClassCreatorProxy { 
  2.     private String mBindingClassName; 
  3.     private String mPackageName; 
  4.     private TypeElement mTypeElement; 
  5.     private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>(); 
  6.     public ClassCreatorProxy(Elements elementUtils, TypeElement classElement) { 
  7.         this.mTypeElement = classElement; 
  8.         PackageElement packageElement = elementUtils.getPackageOf(mTypeElement); 
  9.         String packageName = packageElement.getQualifiedName().toString(); 
  10.         String className = mTypeElement.getSimpleName().toString(); 
  11.         this.mPackageName = packageName; 
  12.         this.mBindingClassName = className + "_ViewBinding"
  13.     } 
  14.     public void putElement(int id, VariableElement element) { 
  15.         mVariableElementMap.put(id, element); 
  16.     } 
  17.     /** 
  18.      * 創(chuàng)建Java代碼 
  19.      * @return 
  20.      */ 
  21.     public String generateJavaCode() { 
  22.         StringBuilder builder = new StringBuilder(); 
  23.         builder.append("package ").append(mPackageName).append(";\n\n"); 
  24.         builder.append("import com.example.gavin.apt_library.*;\n"); 
  25.         builder.append('\n'); 
  26.         builder.append("public class ").append(mBindingClassName); 
  27.         builder.append(" {\n"); 
  28.         generateMethods(builder); 
  29.         builder.append('\n'); 
  30.         builder.append("}\n"); 
  31.         return builder.toString(); 
  32.     } 
  33.     /** 
  34.      * 加入Method 
  35.      * @param builder 
  36.      */ 
  37.     private void generateMethods(StringBuilder builder) { 
  38.         builder.append("public void bind(" + mTypeElement.getQualifiedName() + " host ) {\n"); 
  39.         for (int id : mVariableElementMap.keySet()) { 
  40.             VariableElement element = mVariableElementMap.get(id); 
  41.             String name = element.getSimpleName().toString(); 
  42.             String type = element.asType().toString(); 
  43.             builder.append("host." + name).append(" = "); 
  44.             builder.append("(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));\n"); 
  45.         } 
  46.         builder.append("  }\n"); 
  47.     } 
  48.     public String getProxyClassFullName() 
  49.     { 
  50.         return mPackageName + "." + mBindingClassName; 
  51.     } 
  52.     public TypeElement getTypeElement() 
  53.     { 
  54.         return mTypeElement; 
  55.     } 
  • init:初始化??梢缘玫絇rocessingEnviroment,ProcessingEnviroment提供很多有用的工具類Elements, Types 和 Filer
  • getSupportedAnnotationTypes:指定這個(gè)注解處理器是注冊(cè)給哪個(gè)注解的,這里說明是注解BindView
  • getSupportedSourceVersion:指定使用的Java版本,通常這里返回SourceVersion.latestSupported()
  • process:可以在這里寫掃描、評(píng)估和處理注解的代碼,生成Java文件
  • auto-service 庫:自動(dòng)生成代碼需要借助的庫

4、寫工具類BindViewTools

在aptlib項(xiàng)目中寫綁定類

  1. public class BindViewTools { 
  2.     public static void bind(Activity activity) { 
  3.         Class clazz = activity.getClass(); 
  4.         try { 
  5.             Class bindViewClass = Class.forName(clazz.getName() + "_ViewBinding"); 
  6.             Method method = bindViewClass.getMethod("bind", activity.getClass()); 
  7.             method.invoke(bindViewClass.newInstance(), activity); 
  8.         } catch (Exception e) { 
  9.             e.printStackTrace(); 
  10.         } 
  11.     } 

5、主項(xiàng)目app中引入

  1. implementation project(path: ':aptlib'
  2.  annotationProcessor project(path: ':aptlib-process'

在MainActivity中,在View的前面加上BindView注解,把id傳入即可

  1. public class MainActivity extends AppCompatActivity { 
  2.     @BindView(R.id.tv) 
  3.     TextView mTextView; 
  4.     @BindView(R.id.btn) 
  5.     Button mButton; 
  6.     @Override 
  7.     protected void onCreate(Bundle savedInstanceState) { 
  8.         super.onCreate(savedInstanceState); 
  9.         setContentView(R.layout.activity_main); 
  10.         BindViewTools.bind(this); 
  11.         mTextView.setText("bind TextView success"); 
  12.         mButton.setText("bind Button success"); 
  13.     } 

總結(jié)

1、APT技術(shù)其實(shí)就是自定義注解和注解處理器,在編譯期間生成Java文件,類似于IOC控制反轉(zhuǎn),可以方便的進(jìn)行解耦;

2、如果你也可以實(shí)現(xiàn)很多不同的項(xiàng)目,比如路由框架等等,后續(xù)也會(huì)寫一些apt的項(xiàng)目

 

責(zé)任編輯:武曉燕 來源: Android開發(fā)編程
相關(guān)推薦

2023-03-27 08:28:57

spring代碼,starter

2021-07-14 09:00:00

JavaFX開發(fā)應(yīng)用

2015-04-02 11:22:29

2011-01-10 14:41:26

2011-05-03 15:59:00

黑盒打印機(jī)

2018-05-16 13:50:30

Python網(wǎng)絡(luò)爬蟲Scrapy

2018-05-16 15:46:06

Python網(wǎng)絡(luò)爬蟲PhantomJS

2022-07-27 08:16:22

搜索引擎Lucene

2022-01-08 20:04:20

攔截系統(tǒng)調(diào)用

2022-03-14 14:47:21

HarmonyOS操作系統(tǒng)鴻蒙

2023-04-26 12:46:43

DockerSpringKubernetes

2022-12-07 08:42:35

2021-06-22 10:43:03

Webpack loader plugin

2018-05-22 16:28:46

Python網(wǎng)絡(luò)爬蟲URL去重

2022-03-08 11:17:54

函數(shù)指針回調(diào)函數(shù)C語言

2011-02-22 13:46:27

微軟SQL.NET

2021-02-26 11:54:38

MyBatis 插件接口

2021-12-28 08:38:26

Linux 中斷喚醒系統(tǒng)Linux 系統(tǒng)

2011-04-28 09:23:36

REST

2021-11-24 16:02:57

鴻蒙HarmonyOS應(yīng)用
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)