万能的APT!编译时注解的妙用

22 篇文章 0 订阅
4 篇文章 0 订阅

转载自:http://zjutkz.net/2016/04/07/万能的APT!编译时注解的妙用/

本篇文章会带你了解什么是注解,注解的用法和分类,并且从knight和butterKnife的使用方式和源码着手让你更加了解编译时注解的好处。

不要脸的推广

在开始这篇文章之前,请允许我不要脸的推广一下我写的一个库,使用编译时注解+apt+javapoet去完成白天/夜间模式的切换,现在鲁棒性还不强,我还会继续维护,欢迎大家star和fork。

地址在这,戳我戳我戳我

注解,字面意思是注释,解释,这个东西在jdk 5被添加进来之后发挥了很大的用处。

1
2
3
4
@Override
public void onCreate() {
    super.onCreate();
}

上面这个场景大家几乎每天都会看到吧,上面的那个@Override就是一个注解,它是什么意思呢?

1
2
3
4
5
6
7
8
9
10
11
**
 * Annotation type used to mark methods that override a method declaration in a
 * superclass. Compilers produce an error if a method annotated with @Override
 * does not actually override a method in a superclass.
 *
 * @since 1.5
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

注释写的很清楚了。哦对了,这里要区分两个概念,注解是我们这篇文章的主角,而注释则是用来标注代码用的,如果你高兴你可以这样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间,写字间里程序员;  
//                  程序人员写程序,又拿程序换酒钱。  
//                  酒醒只在网上坐,酒醉还来网下眠;  
//                  酒醉酒醒日复日,网上网下年复年。  
//                  但愿老死电脑间,不愿鞠躬老板前;  
//                  奔驰宝马贵者趣,公交自行程序员。  
//                  别人笑我忒疯癫,我笑自己命太贱;  
//                  不见满街漂亮妹,哪个归得程序员?  

public class MyClass{

}

是不是很炫酷,哈哈哈。好了好了,言归正传,大家在看到上面@Override的代码的时候,如果不了解注解,是不是对上面所写的东西一头雾水呢?@Target是什么鬼?@Retantion又是啥,怎么注解里还用注解呢?没关系,下面让我带大家一起走进注解的世界。(如果有的同学对注解有所了解了,可以选择性的跳过这一段)

了解注解

注解的定义:

注解(也被成为元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便地使用这些数据。 ——————摘自《Thinking in Java》

简单来说注解的作用就是将我们的需要的数据储存起来,在以后的某一个时刻(可能是编译时,也可能是运行时)去调用它。

注解的使用方式:

首先如果你想定义一个注解,那么你必须在类的开头使用@interface这个限定符,像这样

1
2
public @interface MyAnnotation {
}

这样你就完成了一个最简单的注解,可以去使用它了,就像这样

1
2
3
@MyAnnotation
public class TestClass {
}

但是这样的注解并没有什么卵用,因为它什么也没做啊,定义出来干嘛呢?好玩吗?肯定不是,想要注解发挥它的作用,你必须要再写那么一点点代码。首先,刚刚说过,注解的作用是保存一些数据,那怎么保存呢?你可以在你的注解中定义一个属性,像这样

1
2
3
4
public @interface MyAnnotation {

    String value();
}

然后你就可以这样去修饰你想要注解的东西

1
2
3
@MyAnnotation("TestClass")
public class TestClass {
}

这样,通过MyAnnotation这个注解,TestClass类就保存了”TestClass”这样一个String值,但是要怎么拿到这个值呢?是不是也可以用同样的方式去注解一个方法或者一个变量呢?

还记得上面提到的@Override吗?在这个类的上面还有两个注解@Target和@Retantion,它们被成为元注解,什么是元注解呢?元注解就是修饰注解的注解,意思就是你想要选择你的注解在编译期还是运行期其作用,就选择使用@Target,你想要选择你的注解去注解的东西是一个类,方法还是变量,就使用@Retantion。下面看看这两个元注解的具体内容。

Retantion
1
2
3
public @interface Retention {
    RetentionPolicy value();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum RetentionPolicy {
    /**
     * Annotation is only available in the source code.
     */
    SOURCE,
    /**
     * Annotation is available in the source code and in the class file, but not
     * at runtime. This is the default policy.
     */
    CLASS,
    /**
     * Annotation is available in the source code, the class file and is
     * available at runtime.
     */
    RUNTIME
}

Retention注解有一个属性value,是RetentionPolicy类型的,Enum RetentionPolicy是一个枚举类型,
这个枚举决定了Retention注解应该如何去保持,也可理解为Rentention 搭配 RententionPolicy使用。

RetentionPolicy有3个值:CLASS,RUNTIME,SOURCE

用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;
用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时,
所以他们可以用反射的方式读取。
RetentionPolicy.RUNTIME 可以让你从JVM中读取Annotation注解的信息,以便在分析程序的时候使用.

Target
1
2
3
public @interface Target {
    ElementType[] value();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public enum ElementType {
    /**
     * Class, interface or enum declaration.
     */
    TYPE,
    /**
     * Field declaration.
     */
    FIELD,
    /**
     * Method declaration.
     */
    METHOD,
    /**
     * Parameter declaration.
     */
    PARAMETER,
    /**
     * Constructor declaration.
     */
    CONSTRUCTOR,
    /**
     * Local variable declaration.
     */
    LOCAL_VARIABLE,
    /**
     * Annotation type declaration.
     */
    ANNOTATION_TYPE,
    /**
     * Package declaration.
     */
    PACKAGE
}

它有一个属性ElementType也是枚举类型,值就是上面代码中写的这样。

如@Target(ElementType.METHOD) 修饰的注解表示该注解只能用来修饰在方法上。 其他同理。

这样大家清楚了吧?如果你想要你的注解在运行时起作用,并且只能修饰一个类,那你可以这样定义

1
2
3
4
5
6
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {

    String value();
}

注解的分类:

从取值的方式上来说,注解可以分成两类——编译时注解和运行时注解。

运行时注解

运行时注解表示你只能在程序运行时去操作它,那怎么样才能在运行时去操作呢?很简单,使用反射。

有一个非常非常著名的开源库就用到了运行时注解,那就是retrofit,Github上star数破万,现今最火的网络库,特别是结合RxJava来使用。如果大家想了解retrofit内部的源码,大家可以参考这篇文章

好了,说完retrofit,大家有没有想自己动手写一个注解框架呢?这里再给大家推荐一篇文章,hongyang大神写的,看完相信大家会对运行时注解有很好的理解。

编译时注解

既然运行时注解这么屌,那为什么我们这篇文章的主角是编译时注解呢?因为运行时注解毕竟是在程序运行时去进行操作的,用到了反射,在效率方面嘛。。。都懂的,所以,编译时注解势在必行!

上面在介绍运行时注解的时候提到了retrofit,那有没有什么第三方库是使用编译时注解的呢?那真是多了去了。。。daggerbutterKnife,包括谷歌官方推荐的data binding库,都用到了编译时注解,而且,和retrofit不同的是,retrofit的核心是动态代理(个人理解,不喜勿喷。。)而像dagger,dagger2,butterKnife这些库,核心就是编译时注解+APT+动态生成字节码!可见其强大之处。

打造使用编译时注解完成的一个换肤框架——Knight

编译时注解基本使用方式

上面的文章带大家了解了什么注解以及注解的基本使用方式,下面来讲讲今天的主题——编译时注解。

编译时注解,顾名思义,就是编译时去处理的注解,要怎么做呢?下面我一步一步教大家。

一. 新建一个Android Studio工程

这步没什么好说的,跳过跳过。

二. 在工程中创建一个java library并且让我们的app module去依赖这个java库

注意一定要是java library不能是android library,因为如果你新建的是一个android library,javax中的一些你是不能使用的,所以也就没办法完成编译时注解了。

三. 在java library中创建一个注解类
1
2
3
4
5
6
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface MyAnnotation {

    String value();
}

根据我们上面讲到的知识,@Retention(RetentionPolicy.CLASS)表示这是一个在编译器使用的注解,@Target(ElementType.METHOD)表示它可以注解的范围是方法,String value();表示它接受一个String类型的参数。我们可以这样去修饰一个方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MainActivity extends AppCompatActivity {

    @MyAnnotation("onCreate")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @MyAnnotation("print method")
    private String print(){
        return "print!";
    }
}
四. 在java library中创建一个类继承自AbstractProcessor
1
2
3
4
5
6
7
public class MyProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        return false;
    }
}
五.在java library工程的src/main目录上创建resources文件夹
六. 在resources文件夹中创建META-INF包,在META-INF包中创建services包
七. 在services包下创建javax.annotation.processing.Processor文件
八. 在javax.annotation.processing.Processor文件中写下你继承自AbstractProcessor类的那个子类的全完整路径

最终截图如下。

services

好了,至此,准备工作就做完了。这样,在我们的编译器在编译的时候就会去执行我们的processor类中的process方法,我们可以在这个方法中拿到和注解相关的所有东西。这就是所有编译时注解框架的基础。这里我举个最简单的例子吧,打印出我们注解的方法的名称,参数,返回值和注解的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//表示支持的注解类
@SupportedAnnotationTypes("com.example.MyAnnotation")
public class MyProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //取出每一个用MyAnnotation注解的元素
        for(Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)){
            //如果这个元素是一个方法
            if(element.getKind() == ElementKind.METHOD){
                //强转成方法对应的element,同理,如果你的注解是一个类,那你可以强转成TypeElement
                ExecutableElement executableElement = (ExecutableElement)element;

                //打印方法名
                System.out.println(executableElement.getSimpleName());

                //打印方法的返回类型
                System.out.println(executableElement.getReturnType().toString());

                //获取方法所有的参数
                List<? extends VariableElement> params = executableElement.getParameters();
                //逐个打印参数名
                for(VariableElement variableElement : params){
                    System.out.println(variableElement.getSimpleName());
                }

                //打印注解的值
                System.out.println(executableElement.getAnnotation(MyAnnotation.class).value());
            }
            System.out.println("------------------------------");
        }
        return false;
    }
}

这个类的注释已经很清楚了,相信大家都能看懂。好了,现在大家可以尝试着编译一下,在命令行中使用gradle构建

build

如果在编译时出现了如下错误

error

这说明你的java版本有问题,其实很好确定原因的,”bad class file magic or version”,说明子节码里的魔数或者版本号出了问题。

解决的方案就是首先你得确保的你java环境是1.8以下的,并且在你对应的java library的build.gradle中添加sourceCompatibility = “1.7”这句话。

gradle

这样再执行build就不会有问题了~

好了,执行build之后让我们看看terminal中都输出了什么。

output

看到了吗!最后那一堆输出,依次打印上前面我们注解上的两个方法的名字,返回类型,参数名称和注解值,另外说一个细节,看看输出内容的上面一句话,compileDebugJavaWithJavac,javac!这证实了我们的注解确实是在编译的时候去执行的。

好了,上面介绍了编译时注解的简单使用方法,下面开始探究我们的夜间模式框架——Knight。

Knight使用介绍

首先先确定Knight是什么,它是一个用来实现白天/夜间模式切换的框架,现在Android上实现这种业务逻辑的方法其实有不少了,但是我总结了下,有些是直接重置了theme,然后调用activity的recreate()方法;有些是侵入了activity的源码,反射替换了layoutInflater,然后在xml中去定义资源。我觉得两者都有各自不好的地方,前者不好的地方是它会重新刷新activity的生命周期,这样就要自己保存数据,不然会被清空;后者不好的地方在于侵入性太强了,而Knight的特点在于使用注解的方式去保存资源,使用比较简单,低侵入性,并且不会刷新activity的生命周期,先已支持插件式换肤。下面来看看如此使用吧。

我们直接取一个简单的界面来演示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:orientation="vertical"
    android:background="#ffffff"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/change"
        android:text="change"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="change"/>

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="presented by zjutkz!"
        android:textSize="25sp"
        android:textColor="#000000"/>

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/nav_header_day"/>
</LinearLayout>

它的界面展示是这样的

day

我们想要的效果是点击按钮之后切换到夜间模式,整个背景变黑,字颜色变白,然后再换个图片。来看看我们的activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class TestActivity extends AppCompatActivity{

    @Knight(resName = "backgroundColor",nightResId = {R.color.night_background},dayResId = {R.color.day_background})
    @Bind(R.id.container)
    LinearLayout container;

    @Bind(R.id.change)
    Button btn;

    @Knight(resName = "background,textColor",nightResId = {R.color.night_background,R.color.night_text_color},dayResId = {R.color.day_background,R.color.day_text_color})
    @Bind(R.id.tv)
    TextView tv;

    @Knight(resName = "src",nightResId = {R.drawable.nav_header_night},dayResId = {R.drawable.nav_header_day})
    @Bind(R.id.iv)
    ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        ButterKnife.bind(this);
    }

    public void change(View view){
        //KnightUtil.changeToDay(this);
        KnightUtil.changeToNight(this);
    }
}

这里我结合了butterKnife一起使用,注意如果你也和我一样使用了butterKnife,请在对应的build.gradle中加上这样一句代码:

1
2
3
packagingOptions {
    exclude 'META-INF/services/javax.annotation.processing.Processor'
}

可以看到我们的直接在对应的view上添加了@Knight注解,注解里面的值也很好懂,想要替换什么就写什么,注意现在Knight支持四个元素——src,background,backgroundColor和textColor,你只要在注解的第一个值中设置,后面两个值就是对应的夜晚/白天的资源,现在对于颜色只支持在resource文件中定义。当然,Knight也支持注解自定义的方法,具体用法可以去看我github上的demo。

好了,让我们看看点击button以后的界面。

 night

具体我们的Knight是怎么做的呢?这里我不做分析了,大家可以自己去我的github上看代码,基本的原理我上一节已经讲了,里面用到的一个核心依赖javapoet,大家可以去github上查看使用方式,具体的api风格还是比较清晰的,相信大家都能看懂。

butterKnife源码分析

说到butterKnife,大家一定不会陌生,作为Android中最火的几个库之一,它的作用基本就是用来代替传统的findViewById和setOnClickListener等操作,让程序员们不用写大量重复的代码,节省时间。

由于butterKnife的注解类型太多,比如有最常用的Bind,OnClick,还有OnLongClick,OnItemClick等等,这里我就不每一个都分析了,就以OnClick为例,其他的都是异曲同工。

首先来看看butterKnife的使用方式。

你在xml中写了这样一段布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="zjutkz.com.annotationtest.MainActivity">


    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button"/>

</android.support.design.widget.CoordinatorLayout>

然后是java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MainActivity extends AppCompatActivity {

    @Bind(R.id.btn)
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
    }
}

可以看到简单的使用Bind注解并且在开始的时候调用bind()函数就完成了findViewById的工作,是不是很省事呢。

@Bind注解

下面我们来看看Bind注解具体是什么

1
2
3
4
5
@Retention(CLASS) @Target(FIELD)
public @interface Bind {
  /** View ID to which the field will be bound. */
  int[] value();
}

很简单对吧,有了上节的基础,这个注解很容易看懂。@Retention(CLASS)表示它是一个编译时注解,@Target(FIELD)表示它只接受注解参数,而int[] value();则表示它有一个参数是int型的数组,这个int型的数组对应到具体的代码就是R.id.xx。

processor源码

看完Bind注解具体的内容,下面就让我们看看butterKnife的processor都做了什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
package butterknife.internal;

import android.view.View;
import butterknife.Bind;
import butterknife.BindBool;
import butterknife.BindColor;
import butterknife.BindDimen;
import butterknife.BindDrawable;
import butterknife.BindInt;
import butterknife.BindString;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnFocusChange;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;
import butterknife.OnItemSelected;
import butterknife.OnLongClick;
import butterknife.OnPageChange;
import butterknife.OnTextChanged;
import butterknife.OnTouch;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
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.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;

import static javax.lang.model.element.ElementKind.CLASS;
import static javax.lang.model.element.ElementKind.INTERFACE;
import static javax.lang.model.element.ElementKind.METHOD;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.STATIC;
import static javax.tools.Diagnostic.Kind.ERROR;

public final class ButterKnifeProcessor extends AbstractProcessor {
  public static final String SUFFIX = "$$ViewBinder";
  public static final String ANDROID_PREFIX = "android.";
  public static final String JAVA_PREFIX = "java.";
  static final String VIEW_TYPE = "android.view.View";
  private static final String COLOR_STATE_LIST_TYPE = "android.content.res.ColorStateList";
  private static final String DRAWABLE_TYPE = "android.graphics.drawable.Drawable";
  private static final String NULLABLE_ANNOTATION_NAME = "Nullable";
  private static final String ITERABLE_TYPE = "java.lang.Iterable<?>";
  private static final String LIST_TYPE = List.class.getCanonicalName();
  private static final List<Class<? extends Annotation>> LISTENERS = Arrays.asList(//
      OnCheckedChanged.class, //
      OnClick.class, //
      OnEditorAction.class, //
      OnFocusChange.class, //
      OnItemClick.class, //
      OnItemLongClick.class, //
      OnItemSelected.class, //
      OnLongClick.class, //
      OnPageChange.class, //
      OnTextChanged.class, //
      OnTouch.class //
  );

  private Elements elementUtils;
  private Types typeUtils;
  private Filer filer;

  @Override public synchronized void init(ProcessingEnvironment env) {
    super.init(env);

    elementUtils = env.getElementUtils();
    typeUtils = env.getTypeUtils();
    filer = env.getFiler();
  }

  @Override public Set<String> getSupportedAnnotationTypes() {
    Set<String> types = new LinkedHashSet<String>();

    types.add(Bind.class.getCanonicalName());

    for (Class<? extends Annotation> listener : LISTENERS) {
      types.add(listener.getCanonicalName());
    }

    types.add(BindBool.class.getCanonicalName());
    types.add(BindColor.class.getCanonicalName());
    types.add(BindDimen.class.getCanonicalName());
    types.add(BindDrawable.class.getCanonicalName());
    types.add(BindInt.class.getCanonicalName());
    types.add(BindString.class.getCanonicalName());

    return types;
  }

  @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
    Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);

    for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingClass bindingClass = entry.getValue();

      try {
        JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
        Writer writer = jfo.openWriter();
        writer.write(bindingClass.brewJava());
        writer.flush();
        writer.close();
      } catch (IOException e) {
        error(typeElement, "Unable to write view binder for type %s: %s", typeElement,
            e.getMessage());
      }
    }

    return true;
  }

  private Map<TypeElement, BindingClass> findAndParseTargets(RoundEnvironment env) {
    Map<TypeElement, BindingClass> targetClassMap = new LinkedHashMap<TypeElement, BindingClass>();
    Set<String> erasedTargetNames = new LinkedHashSet<String>();

    // Process each @Bind element.
    for (Element element : env.getElementsAnnotatedWith(Bind.class)) {
      try {
        parseBind(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, Bind.class, e);
      }
    }

    // Process each annotation that corresponds to a listener.
    for (Class<? extends Annotation> listener : LISTENERS) {
      findAndParseListener(env, listener, targetClassMap, erasedTargetNames);
    }

    // Process each @BindBool element.
    for (Element element : env.getElementsAnnotatedWith(BindBool.class)) {
      try {
        parseResourceBool(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindBool.class, e);
      }
    }

    // Process each @BindColor element.
    for (Element element : env.getElementsAnnotatedWith(BindColor.class)) {
      try {
        parseResourceColor(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindColor.class, e);
      }
    }

    // Process each @BindDimen element.
    for (Element element : env.getElementsAnnotatedWith(BindDimen.class)) {
      try {
        parseResourceDimen(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindDimen.class, e);
      }
    }

    // Process each @BindDrawable element.
    for (Element element : env.getElementsAnnotatedWith(BindDrawable.class)) {
      try {
        parseResourceDrawable(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindDrawable.class, e);
      }
    }

    // Process each @BindInt element.
    for (Element element : env.getElementsAnnotatedWith(BindInt.class)) {
      try {
        parseResourceInt(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindInt.class, e);
      }
    }

    // Process each @BindString element.
    for (Element element : env.getElementsAnnotatedWith(BindString.class)) {
      try {
        parseResourceString(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        logParsingError(element, BindString.class, e);
      }
    }

    // Try to find a parent binder for each.
    for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
      String parentClassFqcn = findParentFqcn(entry.getKey(), erasedTargetNames);
      if (parentClassFqcn != null) {
        entry.getValue().setParentViewBinder(parentClassFqcn + SUFFIX);
      }
    }

    return targetClassMap;
  }

  private void logParsingError(Element element, Class<? extends Annotation> annotation,
      Exception e) {
    StringWriter stackTrace = new StringWriter();
    e.printStackTrace(new PrintWriter(stackTrace));
    error(element, "Unable to parse @%s binding.\n\n%s", annotation.getSimpleName(), stackTrace);
  }

  private boolean isInaccessibleViaGeneratedCode(Class<? extends Annotation> annotationClass,
      String targetThing, Element element) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify method modifiers.
    Set<Modifier> modifiers = element.getModifiers();
    if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) {
      error(element, "@%s %s must not be private or static. (%s.%s)",
          annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify containing type.
    if (enclosingElement.getKind() != CLASS) {
      error(enclosingElement, "@%s %s may only be contained in classes. (%s.%s)",
          annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify containing class visibility is not private.
    if (enclosingElement.getModifiers().contains(PRIVATE)) {
      error(enclosingElement, "@%s %s may not be contained in private classes. (%s.%s)",
          annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    return hasError;
  }

  private boolean isBindingInWrongPackage(Class<? extends Annotation> annotationClass,
      Element element) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    String qualifiedName = enclosingElement.getQualifiedName().toString();

    if (qualifiedName.startsWith(ANDROID_PREFIX)) {
      error(element, "@%s-annotated class incorrectly in Android framework package. (%s)",
          annotationClass.getSimpleName(), qualifiedName);
      return true;
    }
    if (qualifiedName.startsWith(JAVA_PREFIX)) {
      error(element, "@%s-annotated class incorrectly in Java framework package. (%s)",
          annotationClass.getSimpleName(), qualifiedName);
      return true;
    }

    return false;
  }

  private void parseBind(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    // Verify common generated code restrictions.
    if (isInaccessibleViaGeneratedCode(Bind.class, "fields", element)
        || isBindingInWrongPackage(Bind.class, element)) {
      return;
    }

    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.ARRAY) {
      parseBindMany(element, targetClassMap, erasedTargetNames);
    } else if (LIST_TYPE.equals(doubleErasure(elementType))) {
      parseBindMany(element, targetClassMap, erasedTargetNames);
    } else if (isSubtypeOfType(elementType, ITERABLE_TYPE)) {
      error(element, "@%s must be a List or array. (%s.%s)", Bind.class.getSimpleName(),
          ((TypeElement) element.getEnclosingElement()).getQualifiedName(),
          element.getSimpleName());
    } else {
      parseBindOne(element, targetClassMap, erasedTargetNames);
    }
  }

  private void parseBindOne(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type extends from View.
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
      TypeVariable typeVariable = (TypeVariable) elementType;
      elementType = typeVariable.getUpperBound();
    }
    if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) {
      error(element, "@%s fields must extend from View or be an interface. (%s.%s)",
          Bind.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    // Assemble information on the field.
    int[] ids = element.getAnnotation(Bind.class).value();
    if (ids.length != 1) {
      error(element, "@%s for a view must only specify one ID. Found: %s. (%s.%s)",
          Bind.class.getSimpleName(), Arrays.toString(ids), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    if (hasError) {
      return;
    }

    int id = ids[0];
    BindingClass bindingClass = targetClassMap.get(enclosingElement);
    if (bindingClass != null) {
      ViewBindings viewBindings = bindingClass.getViewBinding(id);
      if (viewBindings != null) {
        Iterator<FieldViewBinding> iterator = viewBindings.getFieldBindings().iterator();
        if (iterator.hasNext()) {
          FieldViewBinding existingBinding = iterator.next();
          error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
              Bind.class.getSimpleName(), id, existingBinding.getName(),
              enclosingElement.getQualifiedName(), element.getSimpleName());
          return;
        }
      }
    } else {
      bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    }

    String name = element.getSimpleName().toString();
    String type = elementType.toString();
    boolean required = isRequiredBinding(element);

    FieldViewBinding binding = new FieldViewBinding(name, type, required);
    bindingClass.addField(id, binding);

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseBindMany(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the type is a List or an array.
    TypeMirror elementType = element.asType();
    String erasedType = doubleErasure(elementType);
    TypeMirror viewType = null;
    FieldCollectionViewBinding.Kind kind = null;
    if (elementType.getKind() == TypeKind.ARRAY) {
      ArrayType arrayType = (ArrayType) elementType;
      viewType = arrayType.getComponentType();
      kind = FieldCollectionViewBinding.Kind.ARRAY;
    } else if (LIST_TYPE.equals(erasedType)) {
      DeclaredType declaredType = (DeclaredType) elementType;
      List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
      if (typeArguments.size() != 1) {
        error(element, "@%s List must have a generic component. (%s.%s)",
            Bind.class.getSimpleName(), enclosingElement.getQualifiedName(),
            element.getSimpleName());
        hasError = true;
      } else {
        viewType = typeArguments.get(0);
      }
      kind = FieldCollectionViewBinding.Kind.LIST;
    } else {
      throw new AssertionError();
    }
    if (viewType != null && viewType.getKind() == TypeKind.TYPEVAR) {
      TypeVariable typeVariable = (TypeVariable) viewType;
      viewType = typeVariable.getUpperBound();
    }

    // Verify that the target type extends from View.
    if (viewType != null && !isSubtypeOfType(viewType, VIEW_TYPE) && !isInterface(viewType)) {
      error(element, "@%s List or array type must extend from View or be an interface. (%s.%s)",
          Bind.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int[] ids = element.getAnnotation(Bind.class).value();
    if (ids.length == 0) {
      error(element, "@%s must specify at least one ID. (%s.%s)", Bind.class.getSimpleName(),
          enclosingElement.getQualifiedName(), element.getSimpleName());
      return;
    }

    Integer duplicateId = findDuplicate(ids);
    if (duplicateId != null) {
      error(element, "@%s annotation contains duplicate ID %d. (%s.%s)", Bind.class.getSimpleName(),
          duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName());
    }

    assert viewType != null; // Always false as hasError would have been true.
    String type = viewType.toString();
    boolean required = isRequiredBinding(element);

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldCollectionViewBinding binding = new FieldCollectionViewBinding(name, type, kind, required);
    bindingClass.addFieldCollection(ids, binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceBool(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is bool.
    if (element.asType().getKind() != TypeKind.BOOLEAN) {
      error(element, "@%s field type must be 'boolean'. (%s.%s)",
          BindBool.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindBool.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindBool.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindBool.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name, "getBoolean");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceColor(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is int or ColorStateList.
    boolean isColorStateList = false;
    TypeMirror elementType = element.asType();
    if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) {
      isColorStateList = true;
    } else if (elementType.getKind() != TypeKind.INT) {
      error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)",
          BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindColor.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindColor.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name,
        isColorStateList ? "getColorStateList" : "getColor");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceDimen(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is int or ColorStateList.
    boolean isInt = false;
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.INT) {
      isInt = true;
    } else if (elementType.getKind() != TypeKind.FLOAT) {
      error(element, "@%s field type must be 'int' or 'float'. (%s.%s)",
          BindDimen.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindDimen.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindDimen.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindDimen.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name,
        isInt ? "getDimensionPixelSize" : "getDimension");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceDrawable(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is Drawable.
    if (!DRAWABLE_TYPE.equals(element.asType().toString())) {
      error(element, "@%s field type must be 'Drawable'. (%s.%s)",
          BindDrawable.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindDrawable.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindDrawable.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindDrawable.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name, "getDrawable");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceInt(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is int.
    if (element.asType().getKind() != TypeKind.INT) {
      error(element, "@%s field type must be 'int'. (%s.%s)", BindInt.class.getSimpleName(),
          enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindInt.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindInt.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindInt.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name, "getInteger");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  private void parseResourceString(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type is String.
    if (!"java.lang.String".equals(element.asType().toString())) {
      error(element, "@%s field type must be 'String'. (%s.%s)",
          BindString.class.getSimpleName(), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindString.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindString.class, element);

    if (hasError) {
      return;
    }

    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindString.class).value();

    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    FieldResourceBinding binding = new FieldResourceBinding(id, name, "getString");
    bindingClass.addResource(binding);

    erasedTargetNames.add(enclosingElement.toString());
  }

  /** Returns the first duplicate element inside an array, null if there are no duplicates. */
  private static Integer findDuplicate(int[] array) {
    Set<Integer> seenElements = new LinkedHashSet<Integer>();

    for (int element : array) {
      if (!seenElements.add(element)) {
        return element;
      }
    }

    return null;
  }

  /** Uses both {@link Types#erasure} and string manipulation to strip any generic types. */
  private String doubleErasure(TypeMirror elementType) {
    String name = typeUtils.erasure(elementType).toString();
    int typeParamStart = name.indexOf('<');
    if (typeParamStart != -1) {
      name = name.substring(0, typeParamStart);
    }
    return name;
  }

  private void findAndParseListener(RoundEnvironment env,
      Class<? extends Annotation> annotationClass, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    for (Element element : env.getElementsAnnotatedWith(annotationClass)) {
      try {
        parseListenerAnnotation(annotationClass, element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        StringWriter stackTrace = new StringWriter();
        e.printStackTrace(new PrintWriter(stackTrace));

        error(element, "Unable to generate view binder for @%s.\n\n%s",
            annotationClass.getSimpleName(), stackTrace.toString());
      }
    }
  }

  private void parseListenerAnnotation(Class<? extends Annotation> annotationClass, Element element,
      Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames)
      throws Exception {
    // This should be guarded by the annotation's @Target but it's worth a check for safe casting.
    if (!(element instanceof ExecutableElement) || element.getKind() != METHOD) {
      throw new IllegalStateException(
          String.format("@%s annotation must be on a method.", annotationClass.getSimpleName()));
    }

    ExecutableElement executableElement = (ExecutableElement) element;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Assemble information on the method.
    Annotation annotation = element.getAnnotation(annotationClass);
    Method annotationValue = annotationClass.getDeclaredMethod("value");
    if (annotationValue.getReturnType() != int[].class) {
      throw new IllegalStateException(
          String.format("@%s annotation value() type not int[].", annotationClass));
    }

    int[] ids = (int[]) annotationValue.invoke(annotation);
    String name = executableElement.getSimpleName().toString();
    boolean required = isRequiredBinding(element);

    // Verify that the method and its containing class are accessible via generated code.
    boolean hasError = isInaccessibleViaGeneratedCode(annotationClass, "methods", element);
    hasError |= isBindingInWrongPackage(annotationClass, element);

    Integer duplicateId = findDuplicate(ids);
    if (duplicateId != null) {
      error(element, "@%s annotation for method contains duplicate ID %d. (%s.%s)",
          annotationClass.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    ListenerClass listener = annotationClass.getAnnotation(ListenerClass.class);
    if (listener == null) {
      throw new IllegalStateException(
          String.format("No @%s defined on @%s.", ListenerClass.class.getSimpleName(),
              annotationClass.getSimpleName()));
    }

    for (int id : ids) {
      if (id == View.NO_ID) {
        if (ids.length == 1) {
          if (!required) {
            error(element, "ID-free binding must not be annotated with @Nullable. (%s.%s)",
                enclosingElement.getQualifiedName(), element.getSimpleName());
            hasError = true;
          }

          // Verify target type is valid for a binding without an id.
          String targetType = listener.targetType();
          if (!isSubtypeOfType(enclosingElement.asType(), targetType)
              && !isInterface(enclosingElement.asType())) {
            error(element, "@%s annotation without an ID may only be used with an object of type "
                    + "\"%s\" or an interface. (%s.%s)",
                    annotationClass.getSimpleName(), targetType,
                enclosingElement.getQualifiedName(), element.getSimpleName());
            hasError = true;
          }
        } else {
          error(element, "@%s annotation contains invalid ID %d. (%s.%s)",
              annotationClass.getSimpleName(), id, enclosingElement.getQualifiedName(),
              element.getSimpleName());
          hasError = true;
        }
      }
    }

    ListenerMethod method;
    ListenerMethod[] methods = listener.method();
    if (methods.length > 1) {
      throw new IllegalStateException(String.format("Multiple listener methods specified on @%s.",
          annotationClass.getSimpleName()));
    } else if (methods.length == 1) {
      if (listener.callbacks() != ListenerClass.NONE.class) {
        throw new IllegalStateException(
            String.format("Both method() and callback() defined on @%s.",
                annotationClass.getSimpleName()));
      }
      method = methods[0];
    } else {
      Method annotationCallback = annotationClass.getDeclaredMethod("callback");
      Enum<?> callback = (Enum<?>) annotationCallback.invoke(annotation);
      Field callbackField = callback.getDeclaringClass().getField(callback.name());
      method = callbackField.getAnnotation(ListenerMethod.class);
      if (method == null) {
        throw new IllegalStateException(
            String.format("No @%s defined on @%s's %s.%s.", ListenerMethod.class.getSimpleName(),
                annotationClass.getSimpleName(), callback.getDeclaringClass().getSimpleName(),
                callback.name()));
      }
    }

    // Verify that the method has equal to or less than the number of parameters as the listener.
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() > method.parameters().length) {
      error(element, "@%s methods can have at most %s parameter(s). (%s.%s)",
          annotationClass.getSimpleName(), method.parameters().length,
          enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    // Verify method return type matches the listener.
    TypeMirror returnType = executableElement.getReturnType();
    if (returnType instanceof TypeVariable) {
      TypeVariable typeVariable = (TypeVariable) returnType;
      returnType = typeVariable.getUpperBound();
    }
    if (!returnType.toString().equals(method.returnType())) {
      error(element, "@%s methods must have a '%s' return type. (%s.%s)",
          annotationClass.getSimpleName(), method.returnType(),
          enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    if (hasError) {
      return;
    }

    Parameter[] parameters = Parameter.NONE;
    if (!methodParameters.isEmpty()) {
      parameters = new Parameter[methodParameters.size()];
      BitSet methodParameterUsed = new BitSet(methodParameters.size());
      String[] parameterTypes = method.parameters();
      for (int i = 0; i < methodParameters.size(); i++) {
        VariableElement methodParameter = methodParameters.get(i);
        TypeMirror methodParameterType = methodParameter.asType();
        if (methodParameterType instanceof TypeVariable) {
          TypeVariable typeVariable = (TypeVariable) methodParameterType;
          methodParameterType = typeVariable.getUpperBound();
        }

        for (int j = 0; j < parameterTypes.length; j++) {
          if (methodParameterUsed.get(j)) {
            continue;
          }
          if (isSubtypeOfType(methodParameterType, parameterTypes[j])
              || isInterface(methodParameterType)) {
            parameters[i] = new Parameter(j, methodParameterType.toString());
            methodParameterUsed.set(j);
            break;
          }
        }
        if (parameters[i] == null) {
          StringBuilder builder = new StringBuilder();
          builder.append("Unable to match @")
              .append(annotationClass.getSimpleName())
              .append(" method arguments. (")
              .append(enclosingElement.getQualifiedName())
              .append('.')
              .append(element.getSimpleName())
              .append(')');
          for (int j = 0; j < parameters.length; j++) {
            Parameter parameter = parameters[j];
            builder.append("\n\n  Parameter #")
                .append(j + 1)
                .append(": ")
                .append(methodParameters.get(j).asType().toString())
                .append("\n    ");
            if (parameter == null) {
              builder.append("did not match any listener parameters");
            } else {
              builder.append("matched listener parameter #")
                  .append(parameter.getListenerPosition() + 1)
                  .append(": ")
                  .append(parameter.getType());
            }
          }
          builder.append("\n\nMethods may have up to ")
              .append(method.parameters().length)
              .append(" parameter(s):\n");
          for (String parameterType : method.parameters()) {
            builder.append("\n  ").append(parameterType);
          }
          builder.append(
              "\n\nThese may be listed in any order but will be searched for from top to bottom.");
          error(executableElement, builder.toString());
          return;
        }
      }
    }

    MethodViewBinding binding = new MethodViewBinding(name, Arrays.asList(parameters), required);
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    for (int id : ids) {
      if (!bindingClass.addMethod(id, listener, method, binding)) {
        error(element, "Multiple listener methods with return value specified for ID %d. (%s.%s)",
            id, enclosingElement.getQualifiedName(), element.getSimpleName());
        return;
      }
    }

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
  }

  private boolean isInterface(TypeMirror typeMirror) {
    if (!(typeMirror instanceof DeclaredType)) {
      return false;
    }
    return ((DeclaredType) typeMirror).asElement().getKind() == INTERFACE;
  }

  private boolean isSubtypeOfType(TypeMirror typeMirror, String otherType) {
    if (otherType.equals(typeMirror.toString())) {
      return true;
    }
    if (typeMirror.getKind() != TypeKind.DECLARED) {
      return false;
    }
    DeclaredType declaredType = (DeclaredType) typeMirror;
    List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
    if (typeArguments.size() > 0) {
      StringBuilder typeString = new StringBuilder(declaredType.asElement().toString());
      typeString.append('<');
      for (int i = 0; i < typeArguments.size(); i++) {
        if (i > 0) {
          typeString.append(',');
        }
        typeString.append('?');
      }
      typeString.append('>');
      if (typeString.toString().equals(otherType)) {
        return true;
      }
    }
    Element element = declaredType.asElement();
    if (!(element instanceof TypeElement)) {
      return false;
    }
    TypeElement typeElement = (TypeElement) element;
    TypeMirror superType = typeElement.getSuperclass();
    if (isSubtypeOfType(superType, otherType)) {
      return true;
    }
    for (TypeMirror interfaceType : typeElement.getInterfaces()) {
      if (isSubtypeOfType(interfaceType, otherType)) {
        return true;
      }
    }
    return false;
  }

  private BindingClass getOrCreateTargetClass(Map<TypeElement, BindingClass> targetClassMap,
      TypeElement enclosingElement) {
    BindingClass bindingClass = targetClassMap.get(enclosingElement);
    if (bindingClass == null) {
      String targetType = enclosingElement.getQualifiedName().toString();
      String classPackage = getPackageName(enclosingElement);
      String className = getClassName(enclosingElement, classPackage) + SUFFIX;

      bindingClass = new BindingClass(classPackage, className, targetType);
      targetClassMap.put(enclosingElement, bindingClass);
    }
    return bindingClass;
  }

  private static String getClassName(TypeElement type, String packageName) {
    int packageLen = packageName.length() + 1;
    return type.getQualifiedName().toString().substring(packageLen).replace('.', '$');
  }

  /** Finds the parent binder type in the supplied set, if any. */
  private String findParentFqcn(TypeElement typeElement, Set<String> parents) {
    TypeMirror type;
    while (true) {
      type = typeElement.getSuperclass();
      if (type.getKind() == TypeKind.NONE) {
        return null;
      }
      typeElement = (TypeElement) ((DeclaredType) type).asElement();
      if (parents.contains(typeElement.toString())) {
        String packageName = getPackageName(typeElement);
        return packageName + "." + getClassName(typeElement, packageName);
      }
    }
  }

  @Override public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
  }

  private void error(Element element, String message, Object... args) {
    if (args.length > 0) {
      message = String.format(message, args);
    }
    processingEnv.getMessager().printMessage(ERROR, message, element);
  }

  private String getPackageName(TypeElement type) {
    return elementUtils.getPackageOf(type).getQualifiedName().toString();
  }

  private static boolean hasAnnotationWithName(Element element, String simpleName) {
    for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
      String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();
      if (simpleName.equals(annotationName)) {
        return true;
      }
    }
    return false;
  }

  private static boolean isRequiredBinding(Element element) {
    return !hasAnnotationWithName(element, NULLABLE_ANNOTATION_NAME);
  }
}

这么长的源码,没关系,我们先看process函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingClass bindingClass = entry.getValue();

    try {
      JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
      Writer writer = jfo.openWriter();
      writer.write(bindingClass.brewJava());
      writer.flush();
      writer.close();
    } catch (IOException e) {
      error(typeElement, "Unable to write view binder for type %s: %s", typeElement,
          e.getMessage());
    }
  }

  return true;
}

先调用了findAndParseTargets()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
private Map<TypeElement, BindingClass> findAndParseTargets(RoundEnvironment env) {
  Map<TypeElement, BindingClass> targetClassMap = new LinkedHashMap<TypeElement, BindingClass>();
  Set<String> erasedTargetNames = new LinkedHashSet<String>();

  // Process each @Bind element.
  for (Element element : env.getElementsAnnotatedWith(Bind.class)) {
    try {
      parseBind(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, Bind.class, e);
    }
  }

  // Process each annotation that corresponds to a listener.
  for (Class<? extends Annotation> listener : LISTENERS) {
    findAndParseListener(env, listener, targetClassMap, erasedTargetNames);
  }

  // Process each @BindBool element.
  for (Element element : env.getElementsAnnotatedWith(BindBool.class)) {
    try {
      parseResourceBool(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindBool.class, e);
    }
  }

  // Process each @BindColor element.
  for (Element element : env.getElementsAnnotatedWith(BindColor.class)) {
    try {
      parseResourceColor(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindColor.class, e);
    }
  }

  // Process each @BindDimen element.
  for (Element element : env.getElementsAnnotatedWith(BindDimen.class)) {
    try {
      parseResourceDimen(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindDimen.class, e);
    }
  }

  // Process each @BindDrawable element.
  for (Element element : env.getElementsAnnotatedWith(BindDrawable.class)) {
    try {
      parseResourceDrawable(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindDrawable.class, e);
    }
  }

  // Process each @BindInt element.
  for (Element element : env.getElementsAnnotatedWith(BindInt.class)) {
    try {
      parseResourceInt(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindInt.class, e);
    }
  }

  // Process each @BindString element.
  for (Element element : env.getElementsAnnotatedWith(BindString.class)) {
    try {
      parseResourceString(element, targetClassMap, erasedTargetNames);
    } catch (Exception e) {
      logParsingError(element, BindString.class, e);
    }
  }

  // Try to find a parent binder for each.
  for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
    String parentClassFqcn = findParentFqcn(entry.getKey(), erasedTargetNames);
    if (parentClassFqcn != null) {
      entry.getValue().setParentViewBinder(parentClassFqcn + SUFFIX);
    }
  }

  return targetClassMap;
}

我们只看和Bind有关的

1
2
3
4
5
6
7
8
// Process each @Bind element.
for (Element element : env.getElementsAnnotatedWith(Bind.class)) {
  try {
    parseBind(element, targetClassMap, erasedTargetNames);
  } catch (Exception e) {
    logParsingError(element, Bind.class, e);
  }
}

调用了parseBind()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void parseBind(Element element, Map<TypeElement, BindingClass> targetClassMap,
    Set<String> erasedTargetNames) {
  // Verify common generated code restrictions.
  if (isInaccessibleViaGeneratedCode(Bind.class, "fields", element)
      || isBindingInWrongPackage(Bind.class, element)) {
    return;
  }

  TypeMirror elementType = element.asType();
  if (elementType.getKind() == TypeKind.ARRAY) {
    parseBindMany(element, targetClassMap, erasedTargetNames);
  } else if (LIST_TYPE.equals(doubleErasure(elementType))) {
    parseBindMany(element, targetClassMap, erasedTargetNames);
  } else if (isSubtypeOfType(elementType, ITERABLE_TYPE)) {
    error(element, "@%s must be a List or array. (%s.%s)", Bind.class.getSimpleName(),
        ((TypeElement) element.getEnclosingElement()).getQualifiedName(),
        element.getSimpleName());
  } else {
    parseBindOne(element, targetClassMap, erasedTargetNames);
  }
}

在parseBind()方法中调用了parseOne()和parseMany()方法,从parseBind()方法中的判断中可以看出,如果被注解的对象是数组或者list就调用parseMany(),否则调用parseOne(),那我们就看parseOne()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
private void parseBindOne(Element element, Map<TypeElement, BindingClass> targetClassMap,
      Set<String> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

    // Verify that the target type extends from View.
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.TYPEVAR) {
      TypeVariable typeVariable = (TypeVariable) elementType;
      elementType = typeVariable.getUpperBound();
    }
    if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) {
      error(element, "@%s fields must extend from View or be an interface. (%s.%s)",
          Bind.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
      hasError = true;
    }

    // Assemble information on the field.
    int[] ids = element.getAnnotation(Bind.class).value();
    if (ids.length != 1) {
      error(element, "@%s for a view must only specify one ID. Found: %s. (%s.%s)",
          Bind.class.getSimpleName(), Arrays.toString(ids), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

    if (hasError) {
      return;
    }

    int id = ids[0];
    BindingClass bindingClass = targetClassMap.get(enclosingElement);
    if (bindingClass != null) {
      ViewBindings viewBindings = bindingClass.getViewBinding(id);
      if (viewBindings != null) {
        Iterator<FieldViewBinding> iterator = viewBindings.getFieldBindings().iterator();
        if (iterator.hasNext()) {
          FieldViewBinding existingBinding = iterator.next();
          error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)",
              Bind.class.getSimpleName(), id, existingBinding.getName(),
              enclosingElement.getQualifiedName(), element.getSimpleName());
          return;
        }
      }
    } else {
      bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement);
    }

    String name = element.getSimpleName().toString();
    String type = elementType.toString();
    boolean required = isRequiredBinding(element);

    FieldViewBinding binding = new FieldViewBinding(name, type, required);
    bindingClass.addField(id, binding);

    // Add the type-erased version to the valid binding targets set.
    erasedTargetNames.add(enclosingElement.toString());
  }

前面是一堆取值+判断,重点是这一句。

1
2
3
4
5
6
7
int[] ids = element.getAnnotation(Bind.class).value();
    if (ids.length != 1) {
      error(element, "@%s for a view must only specify one ID. Found: %s. (%s.%s)",
          Bind.class.getSimpleName(), Arrays.toString(ids), enclosingElement.getQualifiedName(),
          element.getSimpleName());
      hasError = true;
    }

取出Bind注解中的值,也就是各种R.id.xxx,如果长度不为1则报错,因为这是parseOne()方法嘛。

后面的内容就是从map缓存中出去对应的值并且把被Bind注解的变量的名字,类型,id值等等保存起来,如果看过Knight源码的同学应该对这一段轻车熟路了,逻辑都差不多。

让我们回到process()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
  Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env);

  for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) {
    TypeElement typeElement = entry.getKey();
    BindingClass bindingClass = entry.getValue();

    try {
      JavaFileObject jfo = filer.createSourceFile(bindingClass.getFqcn(), typeElement);
      Writer writer = jfo.openWriter();
      writer.write(bindingClass.brewJava());
      writer.flush();
      writer.close();
    } catch (IOException e) {
      error(typeElement, "Unable to write view binder for type %s: %s", typeElement,
          e.getMessage());
    }
  }

  return true;
}

在通过findAndParseTargets()方法保存了对应的值以后,调用了bindingClass.brewJava()方法,让我们跟踪进去看一看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
String brewJava() {
  StringBuilder builder = new StringBuilder();
  builder.append("// Generated code from Butter Knife. Do not modify!\n");
  builder.append("package ").append(classPackage).append(";\n\n");

  if (!resourceBindings.isEmpty()) {
    builder.append("import android.content.res.Resources;\n");
  }
  if (!viewIdMap.isEmpty() || !collectionBindings.isEmpty()) {
    builder.append("import android.view.View;\n");
  }
  builder.append("import butterknife.ButterKnife.Finder;\n");
  if (parentViewBinder == null) {
    builder.append("import butterknife.ButterKnife.ViewBinder;\n");
  }
  builder.append('\n');

  builder.append("public class ").append(className);
  builder.append("<T extends ").append(targetClass).append(">");

  if (parentViewBinder != null) {
    builder.append(" extends ").append(parentViewBinder).append("<T>");
  } else {
    builder.append(" implements ViewBinder<T>");
  }
  builder.append(" {\n");

  emitBindMethod(builder);
  builder.append('\n');
  emitUnbindMethod(builder);

  builder.append("}\n");
  return builder.toString();
}

各种手写代码有木有,其中有一句

1
builder.append(" implements ViewBinder<T>");

这表明我们动态生成的一个java类是要实现ViewBinder的,至于ViewBinder是什么,我们后面再说。

为什么jake大神不用同为square开源的javapoet呢?我也不清楚。。。

到这我们就简单分析完了processor这个类,主要就是通过保存注解相关的内容并且通过javaFileObject去生成java文件。那这个java文件是怎么调用的呢?还记得butterKnife怎么用的吗?

1
ButterKnife.bind(this);

让我们看看bind()函数做了什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void bind(Activity target) {
  bind(target, target, Finder.ACTIVITY);
}

static void bind(Object target, Object source, Finder finder) {
    Class<?> targetClass = target.getClass();
    try {
      if (debug) Log.d(TAG, "Looking up view binder for " + targetClass.getName());
      ViewBinder<Object> viewBinder = findViewBinderForClass(targetClass);
      if (viewBinder != null) {
        viewBinder.bind(finder, target, source);
      }
    } catch (Exception e) {
      throw new RuntimeException("Unable to bind views for " + targetClass.getName(), e);
    }
  }

先不管这个Finder.ACTIVITY是什么鬼,可以看到bind()函数中调用了findViewBinderForClass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private static ViewBinder<Object> findViewBinderForClass(Class<?> cls)
    throws IllegalAccessException, InstantiationException {
  ViewBinder<Object> viewBinder = BINDERS.get(cls);
  if (viewBinder != null) {
    if (debug) Log.d(TAG, "HIT: Cached in view binder map.");
    return viewBinder;
  }
  String clsName = cls.getName();
  if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) {
    if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
    return NOP_VIEW_BINDER;
  }
  try {
    Class<?> viewBindingClass = Class.forName(clsName + ButterKnifeProcessor.SUFFIX);
    //noinspection unchecked
    viewBinder = (ViewBinder<Object>) viewBindingClass.newInstance();
    if (debug) Log.d(TAG, "HIT: Loaded view binder class.");
  } catch (ClassNotFoundException e) {
    if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
    viewBinder = findViewBinderForClass(cls.getSuperclass());
  }
  BINDERS.put(cls, viewBinder);
  return viewBinder;
}

这么多的逻辑,总的来说其实就是通过cls的类型去从map中得到对应的ViewBinder。还记得ViewBinder吗,我们刚刚动态生成的那个java类就是继承自ViewBinder的,我们这里取出的也就是这个ViewBinder。那我们动态生成的java文件在哪儿呢?在/build/generated/source/apt/debud/xxxx/目录下,xxx是你对应的包名。当然你想要看到有对应的java文件,需要在整个工程的build.gradle下添加

1
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

在对应的module下添加

1
apply plugin: 'com.neenbedankt.android-apt'

我们以这样一个简单的activity为例

1
2
3
4
5
6
7
8
9
10
11
12
public class MainActivity extends AppCompatActivity {

    @Bind(R.id.btn)
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
}

来看看动态生成的java类是怎么样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Generated code from Butter Knife. Do not modify!
package zjutkz.com.annotationtest;

import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;

public class MainActivity$$ViewBinder<T extends zjutkz.com.annotationtest.MainActivity> implements ViewBinder<T> {
  @Override public void bind(final Finder finder, final T target, Object source) {
    View view;
    view = finder.findRequiredView(source, 2131492969, "field 'btn'");
    target.btn = finder.castView(view, 2131492969, "field 'btn'");
  }

  @Override public void unbind(T target) {
    target.btn = null;
  }
}

大家可以对照上面的brewJava()方法去看。

看到bind方法了吗?这就是我们activity中调用ButterKnife.bind(this);这个函数以后,最终就会走到这个方法中。调用了finder的两个方法,下面让我们看看finder是什么。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public enum Finder {
  VIEW {
    @Override protected View findView(Object source, int id) {
      return ((View) source).findViewById(id);
    }

    @Override public Context getContext(Object source) {
      return ((View) source).getContext();
    }
  },
  ACTIVITY {
    @Override protected View findView(Object source, int id) {
      return ((Activity) source).findViewById(id);
    }

    @Override public Context getContext(Object source) {
      return (Activity) source;
    }
  },
  DIALOG {
    @Override protected View findView(Object source, int id) {
      return ((Dialog) source).findViewById(id);
    }

    @Override public Context getContext(Object source) {
      return ((Dialog) source).getContext();
    }
  };

首先可以看到Finder是一个枚举,然后来看看findRequiredView()方法做了什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public <T> T findRequiredView(Object source, int id, String who) {
  T view = findOptionalView(source, id, who);
  if (view == null) {
    String name = getContext(source).getResources().getResourceEntryName(id);
    throw new IllegalStateException("Required view '"
        + name
        + "' with ID "
        + id
        + " for "
        + who
        + " was not found. If this view is optional add '@Nullable' annotation.");
  }
  return view;
}

public <T> T findOptionalView(Object source, int id, String who) {
  View view = findView(source, id);
  return castView(view, id, who);
}

@SuppressWarnings("unchecked") // That's the point.
public <T> T castView(View view, int id, String who) {
  try {
    return (T) view;
  } catch (ClassCastException e) {
    if (who == null) {
      throw new AssertionError();
    }
    String name = view.getResources().getResourceEntryName(id);
    throw new IllegalStateException("View '"
        + name
        + "' with ID "
        + id
        + " for "
        + who
        + " was of the wrong type. See cause for more info.", e);
  }
}
protected abstract View findView(Object source, int id);

findRequiredView()方法中调用了findOptionalView()方法,而findOptionalView()方法中调用了findView()方法,而findView()是一个抽象方法。还记得刚刚看到的Finder的定义吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
VIEW {
  @Override protected View findView(Object source, int id) {
    return ((View) source).findViewById(id);
  }

  @Override public Context getContext(Object source) {
    return ((View) source).getContext();
  }
},
ACTIVITY {
  @Override protected View findView(Object source, int id) {
    return ((Activity) source).findViewById(id);
  }

  @Override public Context getContext(Object source) {
    return (Activity) source;
  }
},
DIALOG {
  @Override protected View findView(Object source, int id) {
    return ((Dialog) source).findViewById(id);
  }

  @Override public Context getContext(Object source) {
    return ((Dialog) source).getContext();
  }
};

在每一个枚举量中重写了findView()方法。

而我们Activity.bind()方法中调用的是Finder.ACTIVITY

1
2
3
public static void bind(Activity target) {
  bind(target, target, Finder.ACTIVITY);
}

就会调用对应的

1
2
3
protected View findView(Object source, int id) {
  return ((Activity) source).findViewById(id);
}

完成了findViewById。

为什么要这样设计呢?想象一下findViewById的使用场景,可能是Activity,可能是Fragment,可能是Dialog,可能是View等等等等,如果一股脑儿只写一个bind()方法的话,势必要有大量的强转和if判断,而jake大神采用了这样的方式,让代码的可读性和易维护性大大增强,真的要膜拜他了,真大神啊!!!

好了,到这儿butterKnife的源码也基本简单的分析完了,总的来说就是使用了编译时注解的方式,配合上动态生成java类去帮助大家完成一些工作,比如findViewById。

通过分析Knight和butterKnife的使用和源码,相信大家对编译时注解已经有了一定的了解,可以说这是一个非常使用的框架,配合上javapoet这样的动态生成java子节码的框架可以写出很多“高大上”的代码。大家不妨自己尝试一下!

下期预告

最近MVC,MVP,MVVM的讨论十分之火,这三种框架到底有什么区别呢?有没有什么好的框架能让我们高效的使用它们呢?另外,其实很多人对MVVM,data binding的理解都是存在重大误区的!至于是什么,see you next week.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值