您的位置:首页 > 编程语言 > Java开发

Java注解Annotation详解

2012-06-24 12:36 633 查看
Annotation的声明方式:

Annotation类型那个声明于一般的接口声明极为相似,只是其关键字为@interface,其属性必须带有小括号,其实更像定义方法,下面文章以属性称之。

常见的annotation注解有下面几种:

@Override: 用在方法,说明这个方法打算重写父类中的另一个方法的声明。
@Deprecated: 用于所有元素,说明该方法或属性等已经过时,不建议使用,编译器会产生警告信息,通常是因为它很危险或存在更好的选择。
@SuppressWarnings: 取消显示指定的编译器警告。

在自定义的annotation注解中,主要用到以下这些annotation注解:

@Retention: 表示注释类型的注释要保留多久。其中的RetentionPolicy共有三种策略,分别是:

@SOURCE: 这个Annotation类型的信息只会保存在程序源码中,源码如果经过了编译之后,Annotation的数据就会消失,并不会保存在编译好的.class二进制文件中。
@CLASS: 这个Annotation类型的信息保留在程序源码中,同时也会保存在编译好的.class文件中,在执行的时候并不会加载到JVM中。(默认)
@RUNTIME: 表示在源码、编译好的.class文件中保存信息,在执行的时候会把这些信息加载到JVM中,这样可以使用反射将其信息获取出来。

@Target: 表示注释类型所使用的程序元素的种类。不声明则可以用在任一程序元素中。其中ElementType程序元素类型提供了Java程序中声明的元素的简单分类:

ANNOTATION_TYPE: 注释类型
CONSTRUCTOR: 构造方法
FIELD: 字段(包括枚举常量)
LOCAL_VARIABLE: 局部变量
METHOD: 方法
PACKAGE: 包
PARAMETER: 参数
TYPE: 类Class、接口Interface(包括注释类型Annotation)或枚举Enum

@Documented: 表示某一类型的注释将通过javadoc和类似的默认工具进行文档化,文档化时其注释部分将成为注释元素的公共API的一部分。

下面通过一例子解释一下Annotation:

MyAnnotation.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* 自定义Annotation
* @author WalkingDog
*
*/

@Target(value = {ElementType.TYPE, ElementType.FIELD,
ElementType.METHOD, ElementType.PARAMETER})

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

//成员参数,其修饰符只有public、默认(default)。
//参数成员只能用八种基本类型和String、Enum、Class、annotation等数据类型及其数组形式、
//当自定义annotation中只有一个参数时,最好将参数名定义为value,因为当参数名为value时,在使用注解的时候可以不指定参数名称而直接赋值即可。
//例如Annotation(value = "walkingdog")相当于Annotation("walkingdog")
String[] value() default "Walkingdog";

Sex sex();
}

enum Sex{
MALE, FEMALE;
}


AnnotationDemo.java
@MyAnnotation(sex = Sex.MALE, value = "Hello Walkingdog")
public class AnnotationDemo {

@MyAnnotation(sex = Sex.MALE)
public void say(){

System.out.println("Walkingdog");

}
}


AnnotationTest.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationTest {

public static void main(String[] args) throws Exception {

AnnotationDemo demo = new AnnotationDemo();

Class<?> clazz = demo.getClass();

//判断AnnotationDemo时候用了MyAnnotation的注解
if(clazz.isAnnotationPresent(MyAnnotation.class)){

//返回MyAnnotation类型的注解
MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);

System.out.println(annotation.value()[0]);

}

Method method = clazz.getDeclaredMethod("say", new Class[]{});

Annotation[] annotations = method.getAnnotations();

for(Annotation annotation : annotations){

System.out.println(annotation.annotationType().getName());

}

}
}


打印结果:

Hello Walkingdog

MyAnnotation

转载请注明出处:/article/10963542.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: