`

Java的注解 Annotation

 
阅读更多

Annotation是继承自java.lang.annotation.Annotation的类,用于向程序分析工具或虚拟机提供package class field methed 等方面的信息,除了使用方式外和其他类没什么区别.

注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致.

 

其实jdk就内置了几个我们常用的注解,定义在java.lang包中。它们是: 

 

      @Override 表示当前方法是覆盖父类的方法。 

 

      @Deprecated  表示当前元素是不建议使用的。 

 

      @SuppressWarnings表示关闭一些不当的编译器警告信息。

 

 

下面我们来自己实现一个注解:

 

Annotation的一般形式:

 

public @interface MyAnnotation {  
    String value() default "hahaha";  
}  

 

 

@interface实际上是继承了java.lang.annotation.Annotation,所以定义annotation时不能继承其他annotation或interface. 

    java.lang.annotation.Retention告诉编译器如何对待 Annotation,使用Retention时,需要提供java.lang.annotation.RetentionPolicy的枚举值.

Java代码  

 

public enum RetentionPolicy {  
    SOURCE, // 编译器处理完Annotation后不存储在class中  
    CLASS, // 编译器把Annotation存储在class中,这是默认值  
    RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要  
}   

 

 

    java.lang.annotation.Target告诉编译器Annotation使用在哪些地方,使用需要指定java.lang.annotation.ElementType的枚举值.

Java代码  

 

public enum ElementType {  
    TYPE, // 指定适用点为 class, interface, enum  
    FIELD, // 指定适用点为 field  
    METHOD, // 指定适用点为 method  
    PARAMETER, // 指定适用点为 method 的 parameter  
    CONSTRUCTOR, // 指定适用点为 constructor  
    LOCAL_VARIABLE, // 指定使用点为 局部变量  
    ANNOTATION_TYPE, //指定适用点为 annotation 类型  
    PACKAGE // 指定适用点为 package  
}   

 

 

    java.lang.annotation.Documented用于指定该Annotation是否可以写入javadoc中. 

    java.lang.annotation.Inherited用于指定该Annotation用于父类时是否能够被子类继承. 

Java代码  

 

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
@Documented  //这个Annotation可以被写入javadoc  
@Inherited       //这个Annotation 可以被继承  
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD}) //表示这个Annotation只能用于注释 构造子和方法  
@Retention(RetentionPolicy.CLASS) //表示这个Annotation存入class但vm不读取  
public @interface MyAnnotation {  
    String value() default "hahaha";  
}  

 

 

    java.lang.reflect.AnnotatedElement接口提供了四个方法来访问Annotation

Java代码  

 

public Annotation getAnnotation(Class annotationType);  
public Annotation[] getAnnotations();  
public Annotation[] getDeclaredAnnotations();  
public boolean isAnnotationPresent(Class annotationType);  

 

 

Class、Constructor、Field、Method、Package等都实现了该接口,可以通过这些方法访问Annotation信息,前提是要访问的Annotation指定Retention为RUNTIME. 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics