一、元注解的概念
java中有4个元注解:@retention、@target、@document、@inherited。所谓元注解就是注解的注解。
二、注解介绍
①@retention
@retention——注解的保留位置
注解仅存在于源码中,在class字节码文件中不包含
@retention(retentionpolicy.source)
默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@retention(retentionpolicy.class)
注解会在class字节码文件中存在,在运行时可以通过反射获取到
@retention(retentionpolicy.runtime)
②@target
@target——注解的作用目标
接口、类、枚举、注解
@target(elementtype.type)
字段、枚举的常量
@target(elementtype.field)
方法
@target(elementtype.method)
方法参数
@target(elementtype.parameter)
构造函数
@target(elementtype.constructor)
局部变量
@target(elementtype.local_variable)
注解
@target(elementtype.annotation_type)
包
@target(elementtype.package)
③@document——说明该注解将被包含在javadoc中
④@inherited——说明子类可以继承父类中的该注解
三、例子
@target({elementtype.method})
public @interface annatdemo{
}
@annatdemo注解作用目标是用于对方法注解并保留在运行时的环境中,可利用反射获得一个方法上的注解调用定义的方法。
原帖地址:http://www.cnblogs.com/gordon-yangyibao/archive/2012/08/07/2626340.html