Android开发Android开发Android技术知识

注解的实现原理

2018-04-28  本文已影响278人  涛涛123759

一、注解的底层实现原理

@Target — —注解用于什么地方

ANNOTATION_TYPE,//给注解注解(这貌似把自己不当类来看)
ElementType.FIELD  //注解作用于变量
ElementType.METHOD //注解作用于方法
ElementType.PARAMETER //注解作用于参数
ElementType.CONSTRUCTOR //注解作用于构造方法
ElementType.LOCAL_VARIABLE //注解作用于局部变量
ElementType.PACKAGE //注解作用于包

@Retention — —注解运行状态

 SOURCE, //源码状态运行,
 CLASS, //编译类文件时运行
 RUNTIME //运行时运行

具体的区别如下:

**@Documented — — 生成说明文档,添加类的解释 **

是否会保存到 Javadoc 文档中

** @Inherited — —允许子类继承父类中的注解**

是否可以被继承,默认为 false

二、实现运行时注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnonation {
   String name() default "";
   int Id()  default 0;
}

注解关键字时@interface,然后上面标注为元注解,表示只能修饰方法并且加载到虚拟机中,里面时这个注解所具有的属性,name, id,我们在给方法加注解的时候设置相应的值。

@TestAnnonation(name = "android" , Id = 1)
private void testAnno(){

}

上面我们在一个方法上面添加注解,然后我们通过下面的方法将这个注解打印出来

private void outputAnnoDetail(Class clazz){
    Method [] methods = clazz.getDeclaredMethods();
    for(Method method  : methods) {
        TestAnnonation testAnnonation  = method.getAnnotation(TestAnnonation.class);
        if (testAnnonation != null) {
            Log.d("anonation", "name------>" + testAnnonation.name() + "------>Id------>" + testAnnonation.Id());
        }
    }
}

三、Android注解框架 ButterKnife

主要看一下几个方法:

@Override
public Set<String> getSupportedAnnotationTypes() {
    Set<String> types = new LinkedHashSet<>();
    for (Class<? extends Annotation> annotation : getSupportedAnnotations()) {
      types.add(annotation.getCanonicalName());
    }
    return types;
 }

private Set<Class<? extends Annotation>> getSupportedAnnotations() {
    Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();

    annotations.add(BindArray.class);
    annotations.add(BindBitmap.class);
    annotations.add(BindBool.class);
    annotations.add(BindColor.class);
    annotations.add(BindDimen.class);
    annotations.add(BindDrawable.class);
    annotations.add(BindFloat.class);
    annotations.add(BindInt.class);
    annotations.add(BindString.class);
    annotations.add(BindView.class);
    annotations.add(BindViews.class);
    annotations.addAll(LISTENERS);

    return annotations;
}

上面的方法主要表明会处理哪些注解

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

    for (Map.Entry<TypeElement, BindingSet> entry : bindingMap.entrySet()) {
      TypeElement typeElement = entry.getKey();
      BindingSet binding = entry.getValue();

      JavaFile javaFile = binding.brewJava(sdk);
      try {
        javaFile.writeTo(filer);
      } catch (IOException e) {
       error(typeElement, "Unable to write binding for type %s: %s", typeElement, e.getMessage());
      }
    }

    return true;
 }
上一篇 下一篇

猜你喜欢

热点阅读