Java Annotation

来源:互联网 发布:单片机uart是什么意思 编辑:程序博客网 时间:2024/05/01 20:44
插入到源码中用于工具处理。
可以在源码层面上处理,也可以通过编译器把它纳入到类文件里面。编译器可以对同一类产生包含和不包含注释的class文件。
第三方不能向编译器添加新的注释。

注释的可能用途:
1. 附属文件的自动生成。如部署描述符或者bean信息类
2. 测试、日志、事务语义等代码的自动生成

元数据:关于数据的数据。元数据只有在与工具协同的时候才有用。
public class MyClass{
   @TestCase public void checkRandomInsertions()
}
这儿@TestCase用于注释check方法,注释被当做一个修饰符,和public和static这些的位置相同了。
@TestCase什么事都不会做,等着工具去支持。

注释可以定义成包括元素的形式,比如:
@TestCase(id="12345")
每个注释都必须通过一个”注释接口“进行定义。接口中的方法,对应于注释中的元素。
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
pulic @interface TestCase{
   String id() default "[none]";
}
这儿interface定义的是一个真正的java接口。处理工具接收实现这个接口的对象。
工具可以调用id()方法来检索注释里面的id元素

@Target和@Retention是元注释,注释了@TestCase。
@Target(ElementType.METHOD)表示这个注释可以应用到方法上
@Rentention表示当类文件载入到虚拟机时,注释仍可保留。

例子,注册监听器的例子:
@ActionListenerFor(source="yellowButton")
public void yelloBackground(){
   panel.setBackground(Color.YELLOW);
}
原来的做法是:
  1. 定义个ColorAction实现ActionListener
  2. 在ColorAction里实现actionPerformed(ActionEvent event)方法
  3. 在方法里面setBackground(yellow)
  4. 构造一个ColorAction
  5. 然后button.addActionListener(这个anction)
采用Annotation的方式需要定义interface
import java.lang.Annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionListenerFor{
   String source();
}
前面定义了注释,使用了注释,还需要说明注释用来干嘛
public class ActionListenerInstaller{
   public static void processAnnotations(Object obj){  //调用的时候是processAnnotations(this)
          Class c1 = obj.getClass();
          for(Method m : c1.getDeclareMethods()){
              ActionListenerFor a = m.getAnnotation(ActionListenerFor.class);
              if(a != null){
                  Field f = c1.getDeclaredField(a.source()); //前面把button作为类的成员变量 //a.source button名
                  f.setAccessible(true);
                  addListener(f.get(obj), obj, m); //自己定义的另外一个方法
              }
          }
   }
}
然后调用ActionListenerInstaller.processAnnotations(this);
Class/Field/Method/Package/Constructor这些类都实现了AnnotatedElement接口
  •  <T extends Annotation> getAnnotation(Class<T> annotationClass)
    • 如果存在该元素的指定类型的注释,则返回这些注释,否则返回 null。
  • Annotation[]     getAnnotations() 
    • 返回此元素上存在的所有注释。
  • Annotation[]     getDeclaredAnnotations()
    • 返回直接存在于此元素上的所有注释。(不包含继承来的)
  • boolean     isAnnotationPresent(Class<? extends Annotation> annotationClass)
          如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。
      
              
0 0
原创粉丝点击