Annotation 可用于修饰包 类 构造器 方法 成员变量 参数 局部变量 的声明这些信息存储在 Annation 的 name=value中Annotation是一个接口程序可以通过反射来获取指定程序元素的Annotation对象,然后通过Annotation对象获得注释里的元数据
元 Annotation只能用于修饰一个Annotation定义用于指定被修饰的Annotation可以保留多长时间。
@Retention包含一个RetentionPolicy类型的 value成员变量所以使用@Retention时必须为该value成员变量指定值。
1 RetentionPolicy.CLASS 编译器将把Annotation 记录在class文件中当程序运行时 jvm不再保留Annotation
2 RetentionPolicy.RUNTIME 编译器将把Annotation记录在class文件中当程序运行时 时 jvm保留Annotation程序可以通过反射获取该Annotation
3 RetentionPolicy.SOURCE Annotation只保留在源码中编译器直接丢弃这种Annotation
//编译器直接丢弃 如果Annotation里只有一个vlaue成员变量可以使用该Annotation直接在Annotation后的扩号里指定value成员变量的值
@Retention(RetentionPolicy.SOURCE)
public @interface Testtable()
{
}
@Target只能修饰一个Annotation定义 b包含名为value的成员变量
ElementType.ANNOTATION_TYPE 修饰Annotation
ElementType.CONSTRUCTOR 构造器
ElementType.FIELD 成员变量
ElementType.LOCAL_VARIABLE 局部变量
ElementType.METHOD 方法
ElementType.PACKAGE 包
ElementType.TYPE 修饰类,接口,枚举
@Target(ElementType.FIELD)
public @Interface ActionListenerfor
{
}
@Documented 用于被该注解修饰的Annontion 将被javadoc工具提取成文档
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @Interface testable{
}
使用@inheried 表示它修饰的Annotation将有继承性---如果某个类使用了 @A 修饰,则其子类将自动被@A修饰
定义注解
@Retention(RUNTIME)
@Target(METHOD)
public @interface count {
}
定义注解处理类
//用于处理注解有几个@count注解的方法就输出几
public class ProcessorTest {
public static void process(String clazz) throws SecurityException, ClassNotFoundException
{
//保存@count的个数
int countAnnotation=0;
for(Method m :Class.forName(clazz).getMethods())
{
//判断方法上是否有@count注解
if(m.isAnnotationPresent(count.class));
{
countAnnotation++;
}
}
System.out.println(countAnnotation);
}
}
用@count注解一个类
public class test1 {
@count
public void fun1() {}
public void fun2() {}
@count
public void fun3() {}
public void fun4() {}
}
测试
public class test2 {
public static void main(String[] args) throws SecurityException, ClassNotFoundException {
ProcessorTest.process("test111.test1");
}
}
结果为2
提取Annotation信息的方法
getAnnotation(Class<T> annotationClass):返回该程序元素上存在的指定类型的注释 如果不存在返回null
Annotation[] getAnnotations() 返回该程序元素上存在的所有注释
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 判断该程序元素上是否存在指定类型的注释