一、自定义Annotation步骤
使用@interface关键字定义新的Annotation
//定义一个简单的Annotation类型
public @interface Test{
}
用于修饰程序的类、方法、变量、接口等定义
//使用@Test修饰类定义
@Test
public class MyClass{
}
public class MyClass{
//使用@TestAnnotaion修饰方法
@Test
public void info(){
}
}
定义Annotation成员变量
public @interface MyTag{
//定义两个成员变量的Annotation
//Annotation中的成员变量以方法的形式定义
String name();
int age();
}
使用该Annotation时,为该Annotation的成员变量指定值
public class Test{
//使用成员变量的Annotation时,需要为成员变量指定值
@MyTag(name="xx",age=6)
public void info(){
…
}
...
}
我们还可以为Annotation指定初始值,使用default关键字
public @interface MyTag{
//定义两个成员变量的Annotation
//以default为两个成员变量指定初始值
String name() default "yeeku";
int age() default 32;
}
如果为Annotation的成员变量指定了默认值,使用时则可以不为这些成员变量指定值;
当然,如果为MyTag的成员变量指定了值,则默认值不会起作用;
二、Annotation分类
根据Annotation是否包含成员变量,我们可以把Annotation分为如下两类:
标记Annotation:没有成员定义,仅使用自身存在与否来为我们提供信息;
元数据Annotation:包含成员变量;
三、提取Annotation的信息
Annotatoin不会自己生效,必须由开发者提供相应的工具来提取并处理Annotation信息;
当一个Annotaion类型被定义为运行时Annotaion后,该Annotation才会在运行时可见,JVM才会装载*.class文件时读取保存在class文件中的Annotation;
Annotaion接口:代表程序元素前面的注释;
AnnotatedElement接口:代表程序中可以接受注释的程序元素;
主要有如下几个实现类:Class,Constructor,Field,Method,Package;
通过反射获取某个类的AnnotatedElement对象,调用该对象的如下方法访问Annotataion信息;
getAnnotation(Class<T> annotationClass):返回该程序上存在的制定类型的注释,如果该类型的注释不存在,则返回null;
Annotation[] getAnnotations():返回该程序元素上所存在的所有注释;
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass):判断该程序元素上是否存在指定类型的注释,如果存在返回true,否则返回false;
//获取MyTest类的info方法的所有注释
try {
Annotation[] aArray = Class.forName("codes.chapter14.class3.MyTest").getMethod("m1").getAnnotations();
//遍历所有注释
for(Annotation an : aArray){
System.out.println(an);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
// 获取对象的MyTest 对象的m8方法所包含的所有注释
// 注意,只有在运行时保留的Annotation才能被获取信息
try {
MyTest myTest = new MyTest();
Annotation[] annotations = myTest.getClass().getMethod("m8").getAnnotations();
// 遍历每个注释
for (Annotation annotation : annotations) {
if (annotation instanceof MyTag) {
System.out.println("Annotation is:" + annotation);
// 将tag强制类型转换为MyTag
System.out.println("annotation.name():"+ ((MyTag) annotation).name());
System.out.println("annotation.age():"+ ((MyTag) annotation).age());
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}Java必备:自定义Annotation,布布扣,bubuko.com
原文:http://blog.csdn.net/p106786860/article/details/20833563