注意:在注解中定义属性时它的类型必须是 8 种基本数据类型外加 类、接口、注解及它们的数组。
先说两个元注解:
@Retention作用是定义被它所注解的注解保留多久,一共有三种策略,定义在RetentionPolicy枚举中.
从注释上看:
source:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;被编译器忽略
class:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期
runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
这3个生命周期分别对应于:Java源文件(.java文件) ---> .class文件 ---> 内存中的字节码。
@Target作用是用于描述注解的使用范围,即被描述的注解可以用在什么地方(类上面、属性上面、方法上面等等)
通过反射获取注解的值:
import java.lang.annotation.*;
import java.lang.reflect.Field;
@ClAnnotation(value ="aaa")
public class Test1 {
@MyAnnotation(msg = "id1",id=1)
private int id;
@MyAnnotation(msg = "name1",id=2)
private String name;
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c = Class.forName("com.newbeemall.newbee.Test.Test1");
//获取这个类上的所有注解
Annotation[] annotations = c.getAnnotations();
for(Annotation a:annotations){
System.out.println(a);
}
//获取注解的值
ClAnnotation annotation = (ClAnnotation)c.getAnnotation(ClAnnotation.class);
String value=annotation.value();
System.out.println(value);
//获取指定属性上的值
Field id = c.getDeclaredField("name");
MyAnnotation annotation1 = id.getAnnotation(MyAnnotation.class);
System.out.println(annotation1.msg());
System.out.println(annotation1.id());
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface ClAnnotation{
String value(); //只有一个属性的时候名字最好用value,因为在给属性赋值的时候value可以不用写
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String msg() default "";
int id() default 1;
}
如果没有在@ClAnnotation上面写@Retention(RetentionPolicy.RUNTIME),在运行时会出现空指针异常。
结果: