最近项目要做代码运行耗时分析,需要做一个用于统计代码段运行时间的util,方便结果输出和统计,思考了一下,觉得可以基于注解进行实现
注解相关概念
- 注解在Java中经常用到,相信大家也不会陌生。最常见的莫过于override,用于标记代码重写父类的方法。使用注解可以在一定程度上简化代码。
- 一些常见的开源库也是采用了注解的方式:
- Butterknife
- Butterknife是为人熟知的Android view注入框架,常用的注解有@BindView,查看@BindView的代码如下
@Retention(CLASS) @Target(FIELD) public @interface BindView { /** View ID to which the field will be bound. */ @IdRes int value(); }
- 使用Butterknife的时候,通过调用 Butterknife.bind()使得注解生效,查看Butterknife.bind()的源码如下
bind()函数获取了当前window的最顶层view,然后调用了createBinding,主要的绑定操作在这之后的函数中@NonNull @UiThread public static Unbinder bind(@NonNull Activity target) { View sourceView = target.getWindow().getDecorView(); return createBinding(target, sourceView); }
findBindingConstructorForClass函数就不做具体的分析了,可以理解为,Butterknife使用注解在编译时生成新的class,相当于帮使用者进行了findViewById()等操作。private static Unbinder createBinding(@NonNull Object target, @NonNull View source) { Class<?> targetClass = target.getClass(); Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass); ... }
- Butterknife是为人熟知的Android view注入框架,常用的注解有@BindView,查看@BindView的代码如下
- EventBus
- EventBus是一种用于Android的发布/订阅事件总线,常用的注解有@Subscribe,查看@Subscribe的代码如下:
Ev@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Subscribe { ThreadMode threadMode() default ThreadMode.POSTING; boolean sticky() default false; int priority() default 0; }
- EventBus是一种用于Android的发布/订阅事件总线,常用的注解有@Subscribe,查看@Subscribe的代码如下:
- Butterknife