Annotation注解可以定义在类或方法上,我们可以通过反射取得所定义的Annotation信息。在java.lang.Class类中提供了取得注解信息的方法,下面是取得注解信息的示例:
注解类的作用范围: CLASS SOURCE RUNTIME
/**
* 反射与注解 自定义Annotation
*/
@SuppressWarnings("serial")
@Deprecated
class Member implements Serializable {
private int name;
@Deprecated
@Override
public String toString() {
return "Member{" +
"name=" + name +
'}';
}
}
/**
* 自定义Annotation @interface表明声明注解
* 定义注解类的定义范围
*/
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
public String name() default "用户";
public int age() default 20;
}
//此处若不赋值,便会使用默认值
//@MyAnnotation(name = "张三",age = 20)
@MyAnnotation
@Deprecated
class Member1{
}
测试:
public class Test{
public static void main(String[] args) {
//取得定义类上的注解 每个注解本身有自己的保存范围
Annotation[] a= Member.class.getAnnotations();
System.out.println("取得定义类上的注解....");
for (Annotation temp:a) {
System.out.println(temp);
}
//取得方法上的注解
System.out.println("取得方法上的注解....");
try {
Annotation[] ant=Member.class.getMethod("toString").getAnnotations();
for (Annotation temp:ant) {
System.out.println(temp);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//取得自定义注解
System.out.println("取得自定义注解....");
Annotation[] ant=Member1.class.getAnnotations();
for (Annotation temp:ant) {
System.out.println(temp);
}
}
}