Android注解使用之通过annotationProcessor注解生成代码实现自己的ButterKnife框架
544
8年前
<h3>前言:</h3> <p>Annotation注解在Android的开发中的使用越来越普遍,例如EventBus、ButterKnife、Dagger2等,之前使用注解的时候需要利用反射机制势必影响到运行效率及性能,直到后来android-apt的出现通过注解根据反射机制动态编译生成代码的方式来解决在运行时不再使用发射机制,不过随着android-apt的退出不再维护,我们今天利用Android studio的官方插件annotationProcessor来实现一下自己的ButterKnife UI注解框架。</p> <h3>需要了解的知识:</h3> <ul> <li> <p><a href="/misc/goto?guid=4959715469602248896" rel="nofollow,noindex">Java学习之注解Annotation实现原理</a></p> </li> <li> <p><a href="/misc/goto?guid=4959729530425873228" rel="nofollow,noindex">Java学习之反射机制及应用场景</a></p> </li> <li> <p><a href="/misc/goto?guid=4959729530514672246" rel="nofollow,noindex">Android注解使用之注解编译android-apt如何切换到annotationProcessor</a></p> </li> <li> <p><a href="/misc/goto?guid=4959729530598815969" rel="nofollow,noindex">Android注解使用之ButterKnife 8.0注解使用介绍</a></p> </li> </ul> <h3>自动成代码:</h3> <p>1.)先看下整个项目结构</p> <p style="text-align:center"><img src="https://simg.open-open.com/show/ada8a452981a674f7c078556aa5bba50.png"></p> <p>整个项目分一个app、app.api、app.annotation、app.complier</p> <p>app:整个项目的入口 用于测试注解框架</p> <p>app.annotation:主要用于申明app所有使用的UI注解</p> <p>app.api:用于申明UI注解框架的api</p> <p>app.complier:用于在编译期间通过反射机制自动生成代码</p> <p>2.)app.annotation 声明注解框架中要使用的注解</p> <p>这里我声明了一个BindView注解,声明周期为Class,作用域为成员变量</p> <pre> <code class="language-java">@Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) public @interface BindView { int value(); } </code></pre> <p>因为这里仅仅想要实现绑定View控件,这里就声明了一个BindView注解</p> <p>注意:</p> <p>app.annotation module为java library,build.gradle配置如下</p> <pre> <code class="language-java">apply plugin: 'java' sourceCompatibility =JavaVersion.VERSION_1_7 targetCompatibility =JavaVersion.VERSION_1_7 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) } </code></pre> <p>3.)app.api 声明UI注解框架中使用的api,比如绑定解绑,查找View控件等</p> <p>面向接口编程,定义一个绑定注解的接口</p> <pre> <code class="language-java">/** * UI绑定解绑接口 * * @param <T> */ public interface ViewBinder<T> { void bindView(T host, Object object, ViewFinder finder); void unBindView(T host); } </code></pre> <p>定义一个被绑定者查找view的接口</p> <pre> <code class="language-java">/** * ui提供者接口 */ public interface ViewFinder { View findView(Object object, int id); } </code></pre> <p>这里声明一个Activity 默认的View查找者</p> <pre> <code class="language-java">/** * Activity UI查找提供者 */ public class ActivityViewFinder implements ViewFinder { @Override public View findView(Object object, int id) { return ((Activity) object).findViewById(id); } } </code></pre> <p>注解框架向外提供绑定方法,这里使用静态类来管理</p> <pre> <code class="language-java">public class LCJViewBinder { private static final ActivityViewFinder activityFinder = new ActivityViewFinder();//默认声明一个Activity View查找器 private static final Map<String, ViewBinder> binderMap = new LinkedHashMap<>();//管理保持管理者Map集合 /** * Activity注解绑定 ActivityViewFinder * * @param activity */ public static void bind(Activity activity) { bind(activity, activity, activityFinder); } /** * '注解绑定 * * @param host 表示注解 View 变量所在的类,也就是注解类 * @param object 表示查找 View 的地方,Activity & View 自身就可以查找,Fragment 需要在自己的 itemView 中查找 * @param finder ui绑定提供者接口 */ private static void bind(Object host, Object object, ViewFinder finder) { String className = host.getClass().getName(); try { ViewBinder binder = binderMap.get(className); if (binder == null) { Class<?> aClass = Class.forName(className + "$$ViewBinder"); binder = (ViewBinder) aClass.newInstance(); binderMap.put(className, binder); } if (binder != null) { binder.bindView(host, object, finder); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * 解除注解绑定 ActivityViewFinder * * @param host */ public static void unBind(Object host) { String className = host.getClass().getName(); ViewBinder binder = binderMap.get(className); if (binder != null) { binder.unBindView(host); } binderMap.remove(className); } } </code></pre> <p>4.)app.complier根据注解在编译期间自动生成java代码</p> <p>优先需要自定义一个AbstractProcessor,然后Annotation生成代码,完整的AbstractProcessor</p> <pre> <code class="language-java">public class LCJViewBinderProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment env){ } @Override public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { } @Override public Set<String> getSupportedAnnotationTypes() { } @Override public SourceVersion getSupportedSourceVersion() { } } </code></pre> <p>重要函数解说</p> <ul> <li>init(ProcessingEnvironment env): 每一个注解处理器类都必须有一个空的构造函数。然而,这里有一个特殊的init()方法,它会被注解处理工具调用,并输入ProcessingEnviroment参数。ProcessingEnviroment提供很多有用的工具类Elements,Types和Filer。</li> <li> <p>public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env)这相当于每个处理器的主函数main()。 在这里写扫描、评估和处理注解的代码,以及生成Java文件。输入参数RoundEnviroment,可以让查询出包含特定注解的被注解元素。</p> </li> <li>getSupportedAnnotationTypes();这里必须指定,这个注解处理器是注册给哪个注解的。注意,它的返回值是一个字符串的集合,包含本处理器想要处理的注解类型的合法全称。换句话说,在这里定义你的注解处理器注册到哪些注解上。 </li> <li>getSupportedSourceVersion();用来指定你使用的Java版本。</li> </ul> <p>该module同样是Java Library,build.gradle配置如下</p> <pre> <code class="language-java">apply plugin: 'java' //apply plugin: 'com.github.dcendents.android-maven' sourceCompatibility =JavaVersion.VERSION_1_7 targetCompatibility =JavaVersion.VERSION_1_7 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.google.auto.service:auto-service:1.0-rc2' compile 'com.squareup:javapoet:1.7.0' compile project(':app.annotation') } </code></pre> <ul> <li> <p>com.google.auto.service:auto-service:1.0-rc2 谷歌提供的Java 生成源代码库</p> </li> <li> <p>com.squareup:javapoet:1.7.0 提供了各种 API 让你用各种姿势去生成 Java 代码文件</p> </li> </ul> <p>定义一个被注解类对象AnnotedClass,用于保存哪些被注解的对象</p> <pre> <code class="language-java">class AnnotatedClass { private static class TypeUtil { static final ClassName BINDER = ClassName.get("com.whoislcj.appapi", "ViewBinder"); static final ClassName PROVIDER = ClassName.get("com.whoislcj.appapi", "ViewFinder"); } private TypeElement mTypeElement; private ArrayList<BindViewField> mFields; private Elements mElements; AnnotatedClass(TypeElement typeElement, Elements elements) { mTypeElement = typeElement; mElements = elements; mFields = new ArrayList<>(); } void addField(BindViewField field) { mFields.add(field); } JavaFile generateFile() { //generateMethod MethodSpec.Builder bindViewMethod = MethodSpec.methodBuilder("bindView") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(TypeName.get(mTypeElement.asType()), "host") .addParameter(TypeName.OBJECT, "source") .addParameter(TypeUtil.PROVIDER, "finder"); for (BindViewField field : mFields) { // find views bindViewMethod.addStatement("host.$N = ($T)(finder.findView(source, $L))", field.getFieldName(), ClassName.get(field.getFieldType()), field.getResId()); } MethodSpec.Builder unBindViewMethod = MethodSpec.methodBuilder("unBindView") .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.get(mTypeElement.asType()), "host") .addAnnotation(Override.class); for (BindViewField field : mFields) { unBindViewMethod.addStatement("host.$N = null", field.getFieldName()); } //generaClass TypeSpec injectClass = TypeSpec.classBuilder(mTypeElement.getSimpleName() + "$$ViewBinder") .addModifiers(Modifier.PUBLIC) .addSuperinterface(ParameterizedTypeName.get(TypeUtil.BINDER, TypeName.get(mTypeElement.asType()))) .addMethod(bindViewMethod.build()) .addMethod(unBindViewMethod.build()) .build(); String packageName = mElements.getPackageOf(mTypeElement).getQualifiedName().toString(); return JavaFile.builder(packageName, injectClass).build(); } } </code></pre> <p>然后再定义一个BindViewField对象用于被注解的成员变量</p> <pre> <code class="language-java">class BindViewField { private VariableElement mVariableElement; private int mResId; BindViewField(Element element) throws IllegalArgumentException { if (element.getKind() != ElementKind.FIELD) { throw new IllegalArgumentException(String.format("Only fields can be annotated with @%s", BindView.class.getSimpleName())); } mVariableElement = (VariableElement) element; BindView bindView = mVariableElement.getAnnotation(BindView.class); mResId = bindView.value(); if (mResId < 0) { throw new IllegalArgumentException( String.format("value() in %s for field %s is not valid !", BindView.class.getSimpleName(), mVariableElement.getSimpleName())); } } /** * 获取变量名称 * * @return */ Name getFieldName() { return mVariableElement.getSimpleName(); } /** * 获取变量id * * @return */ int getResId() { return mResId; } /** * 获取变量类型 * * @return */ TypeMirror getFieldType() { return mVariableElement.asType(); } } </code></pre> <p>上面两个对象定义好了之后,就下来实现一下根据注解生成代码过程</p> <pre> <code class="language-java">@AutoService(Processor.class) public class LCJViewBinderProcessor extends AbstractProcessor { private Filer mFiler; //文件相关的辅助类 private Elements mElementUtils; //元素相关的辅助类 private Messager mMessager; //日志相关的辅助类 private Map<String, AnnotatedClass> mAnnotatedClassMap; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); mFiler = processingEnv.getFiler(); mElementUtils = processingEnv.getElementUtils(); mMessager = processingEnv.getMessager(); mAnnotatedClassMap = new TreeMap<>(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { mAnnotatedClassMap.clear(); try { processBindView(roundEnv); } catch (IllegalArgumentException e) { e.printStackTrace(); error(e.getMessage()); } for (AnnotatedClass annotatedClass : mAnnotatedClassMap.values()) { try { annotatedClass.generateFile().writeTo(mFiler); } catch (IOException e) { error("Generate file failed, reason: %s", e.getMessage()); } } return true; } private void processBindView(RoundEnvironment roundEnv) throws IllegalArgumentException { for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) { AnnotatedClass annotatedClass = getAnnotatedClass(element); BindViewField bindViewField = new BindViewField(element); annotatedClass.addField(bindViewField); } } private AnnotatedClass getAnnotatedClass(Element element) { TypeElement typeElement = (TypeElement) element.getEnclosingElement(); String fullName = typeElement.getQualifiedName().toString(); AnnotatedClass annotatedClass = mAnnotatedClassMap.get(fullName); if (annotatedClass == null) { annotatedClass = new AnnotatedClass(typeElement, mElementUtils); mAnnotatedClassMap.put(fullName, annotatedClass); } return annotatedClass; } private void error(String msg, Object... args) { mMessager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args)); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public Set<String> getSupportedAnnotationTypes() { Set<String> types = new LinkedHashSet<>(); types.add(BindView.class.getCanonicalName()); return types; } } </code></pre> <p>原理是现解析保存被注解的类,然后再根据注解解析被注解的成员变量,进行保存,最后根据生成java类进行写文件</p> <p>5.)app真正使用注解框架应用</p> <p>在build.gradle中添加如下配置</p> <pre> <code class="language-java">dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' compile project(':app.api') compile project(':app.annotation') annotationProcessor project(':app.compiler') } </code></pre> <p>Activity中使用</p> <pre> <code class="language-java">public class MainActivity extends AppCompatActivity { @BindView(R.id.test) Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LCJViewBinder.bind(this); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show(); } }); } @Override protected void onDestroy() { super.onDestroy(); LCJViewBinder.unBind(this); } } </code></pre> <p>然后把项目重新build一下就会自动生成MainActivity$$ViewBinder类</p> <pre> <code class="language-java">public class MainActivity$$ViewBinder implements ViewBinder<MainActivity> { @Override public void bindView(MainActivity host, Object source, ViewFinder finder) { host.mButton = (Button)(finder.findView(source, 2131427413)); } @Override public void unBindView(MainActivity host) { host.mButton = null; } } </code></pre> <h3>总结:</h3> <p>通过注解生成代码在平时的开发过程中可能很少接触,因为目前很多开源框架帮我们处理了这部分,如果我们需要自己做一个使用注解的框架就需要这方面知识了,这个例子仅仅是我自己查找资源然后模仿做出来的,其实我们项目中业务组件化之间可以通过注解来声明路由scheme地址,后期有时间实现一下。</p> <p> </p> <p>来自:http://www.cnblogs.com/whoislcj/p/6168641.html</p> <p> </p>