在java编译器中构建java
编译器开始执行未执行过的注解处理器markdown
玄幻处理注解元素,找到被该住解所修饰的类,方法或者属性this
生成对应的类,并写入文件编码
判断是否全部的注解处理器都已执行完毕,若是没有,继续下一个注解处理器的执行(回到步骤1)spa
主要须要两个库的AutoService
和Javapoet
,对全部的注解进行处理并生成以_BindView
结尾的辅助类辅助类中是注解的实现(findViewByid,onCclick等)code
注解处理器须要实现AbstractProcessor接口,并实现对应的方法:init(),getSupportedSourceVersion(),getSupportedAnnotationTypes()
,(返回所须要的处理的注解被process()方法接收), process() 方法必须实现,扫描全部备注接的元素并作处理,在这里完成了目标类信息的收集并生成对应 java 类,返回值类型是boolean,true表示该注解已被处理,不但愿下一个注解处理器继续处理,false表示未被处理,下一个注解处理器继续处理orm
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface BindView {
int value();
}
复制代码
@BindView(R.id.text1)
TextView textView1;
@BindView(R.id.text2)
TextView textView2;
复制代码
public static void bind(Activity activity) {
bindView(activity);
}
//经过反射实现注解的绑定
public static void bindView(Activity activity) {
try {
// 获取字节码对象
Class<? extends Activity> aClass = activity.getClass();
// 获取所有变量
Field[] fields = aClass.getDeclaredFields();
// 遍历所有变量
for (Field field : fields) {
// 容许暴力反射
field.setAccessible(true);
// 获取带有注解BindView的变量
BindView annotation = field.getAnnotation(BindView.class);
if (annotation != null) {
// 获取注解的值
int value = annotation.value();
View view = activity.findViewById(value);
field.set(activity, view);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
复制代码