💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 代码结构 ![](https://img.kancloud.cn/01/c8/01c8d0456046afa1f01b9616982902b7_529x312.png) * butterknife ;android library model 提供android使用的API * butterknife-annotations; java-model,使用时的注解 * butterknife-compiler;java-model,编译时用到的注解的处理器 * butterknife-gradle-plugin;自定义的gradle插件,辅助生成有关代码 * butterknife-integration-test;该项目的测试用例 * butterknife-lint;该项目的lint检查 * sample;demo ## annotations ### @Bind ~~~ @Retention(CLASS) @Target(FIELD) public @interface Bind { /** View ID to which the field will be bound. */ @IdRes int[] value(); } ~~~ ### @OnClick ~~~ public @interface OnClick { /** View IDs to which the method will be bound. */ @IdRes int[] value() default { View.NO_ID }; } ~~~ ## compiler 源码咱们先忽略,主要使用javapoet生成代码,我们先看处理之后的效果 ![](https://img.kancloud.cn/bc/56/bc56d4d25832e9e7b2a3ff0d33606b83_284x45.png) **AnnotationActivity** ~~~ public class AnnotationActivity extends Activity { @Bind({2131558508}) Button button; @OnClick({2131558508}) public void Onclick(){ Toast.makeText(this, "helloWorld", 0).show(); } protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(2130968601); ButterKnife.bind(this); ~~~ **生成的AnnotationActivity$$ViewBinder** ~~~ public class AnnotationActivity$$ViewBinder<T extends AnnotationActivity> implements ButterKnife.ViewBinder<T> { public void bind(ButterKnife.Finder paramFinder, final T paramT, Object paramObject) { View localView = (View)paramFinder.findRequiredView(paramObject, 2131558508, "field 'button' and method 'Onclick'"); paramT.button = ((Button)paramFinder.castView(localView, 2131558508, "field 'button'")); localView.setOnClickListener(new DebouncingOnClickListener() { public void doClick(View paramAnonymousView) { paramT.Onclick(); } }); } public void unbind(T paramT) { paramT.button = null; ~~~ ## API 入口函数为ButterKnife.bind(this) ![](https://img.kancloud.cn/c8/0a/c80a7e52058aeeb45976d689f04431d1_862x709.png) bind函数根据调用的类名查找其对应的className\_ViewBinding的类名,然后反射调用其构造函数。 ## 参考资料 [深入理解ButterKnife源码并掌握原理(一)](https://blog.csdn.net/ta893115871/article/details/52497297) [ButterKnife源码解析](https://www.jianshu.com/p/036a635da941)