Java的annotation

来源:互联网 发布:sql表增加字段 编辑:程序博客网 时间:2024/06/05 17:36

转载自:http://standalone.iteye.com/blog/1751104

从oracle的官方文档来学习annotations:

地址在: http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html

总结如下:

Annotations我理解就是程序的一些元数据,没有它程序也是ok的。它的主要用途体现在以下几个方面:

1. 替代以前简单的注释;

比如以前的注释可能是:
 

class My Class {}

用Annotations可以写成:
 


再复杂一点的注释:



用Annotations:



其中,@interface是定义一个annotation的关键字,看上去像接口,其实不是。
如果要让@ClassPreamble的信息出现在javadoc生成的文档中,你必须给刚才定义的@ClassPreamble加上@Documented这个保留的annotation。

如下所示:



2. 编译器保留的注解, 例如@Deprecated, @Override, 和 @SuppressWarnings.

@Deprecated意思是这个方法过时了,你最好不要再用了,你用我就给你来个warning;
@Override是提示你这个方法是覆盖了父类的一个方法;
@SuppressWarnings是告诉编译器这个方法可能会抛出warning,但你不要告诉我啦。

3. 在runtime用这些注解信息;
一般的用法在runtime的时候JVM不会load这些annotation信息,如果要让runtime知道,就要使用java.lang.annotation.RetentionPolicy了,这是个enum,有三个可选值,
分别是
  • CLASS:annotation会被记录在class文件里但不会被jvm load。
  • RUNTIME:记录在class文件里也会被jvm load,可以通过反射读取。
  • SOURCE:会被compiler丢弃。


具体看下面这个例子:

先定义一个annotation:



@Retention(RetentionPolicy.RUNTIME) 就是上面所说的在runtime时候我也要知道注解的信息。

@Target(ElementType.FIELD) 是指这个注解可以加在Field前面(所以你加到方法签名会编译不过的),java.lang.annotation.ElementType也是一个enum,其他可选择的值包括如下,不翻译了。

CONSTRUCTOR
Constructor declaration
FIELD
Field declaration (includes enum constants)
LOCAL_VARIABLE
Local variable declaration
METHOD
Method declaration
PACKAGE
Package declaration
PARAMETER
Parameter declaration
TYPE
Class, interface (including annotation type), or enum declaration

定义了这个注解,看怎么在runtime时候访问它:




注意在变量str前面使用了定义的注解,在main方法里通过反射获取到了注解中doTestTarget对应的值,所以输出是

Hello World ! 

原创粉丝点击