Java Annotation——由butterknife想到

butterknife是Android开发中应用非常广泛的一个库。butterknife库主要利用了Java中的注解功能,可以提高Android应用的开发效率,毕竟没几个人会喜欢写那种冗长乏味的页面布局、事件连接的代码。首先,还是给一个典型的butterknife使用代码:

    @BindView(R.id.btn)
    TextView mBtn;

这两行代码,就实现了把布局文件与TextView连接起来的功能,看起来确实非常简单。那么这么方便的功能是如何实现的呢?首先,还是看一个简答的例子,代码如下:

SimpleAnnotation.java
package basicTest;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


@Retention(RUNTIME) @Target(FIELD)
public @interface SimpleAnnotation {
    public int value();
}
Main.java
package basicTest;

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) {
        trackAnnotation(Main.class);
        System.out.println("end");
    }
    
    public static void trackAnnotation(Class<?> cl) {
        for(Field field:cl.getDeclaredFields()){
            SimpleAnnotation info = field.getAnnotation(SimpleAnnotation.class);
            System.out.println(field);
            if(info != null) {
                System.out.println(info.value());
            } else{
                System.out.println("info is empty");
            }
        }
    }

    @SimpleAnnotation(23)
    int value1;
    
    @SimpleAnnotation(24)
    int value2;
}

运行结果

  • int basicTest.Main.value1
  • 23
  • int basicTest.Main.value2
  • 24
  • end

从上面的例子可以看出,Annotation会在类中添加注解的消息,所以利用这些信息就可能实现butterknife的类似功能。当然这里的注解是Runtime时的,而butterknife使用的是Class级别的注解。周末花了半天时间,准备写出一个玩具版的butterknife,结果主体代码写的差不多时,却在调试的时候卡了壳,等有空再调了。

发表评论