自定义注解
一、什么是注解(Annotation)?
注解也叫元数据,是一种代码级别的说明。 是 java5.0 引入的一种注释机制 ,与类、接口、枚举是在统一层次,他可以声明在类、属性、方法、局部变量、方法参数等前面,对这些数据进行说明、注释。
二、自定义注解的声明
1、 元注解
作用: 元注解就是负责注解其他注解 。
1.1 @Target
表明该注解可以应用的java元素类型
target类型 | 描述 |
---|---|
CONSTRUCTOR | 表示注解能用于构造器 |
FIELD | 表示注解能用于域 |
LOCAL_VARIABLE | 表示注解能用于局部变量 |
METHOD | 表示注解能用于方法 |
PACKAGE | 表示注解能用于包 |
PARAMETER | 表示注解能用于方法参数 |
TYPE | 表示注解能用于描述类、接口、或枚举声明 |
1.2 @Retention
表明该注解的生命周期
生命周期类型 | 方法描述 |
---|---|
SOURCE | 在源文件中有效(即源文件保留) |
CLASS | 在class文件中有效(即class保留)默认值 |
RUNTIME | 在运行时有效(即运行时保留) |
1.3 @Document
表明该注解标记的元素可以被Javadoc 或类似的工具文档化
1.4 @Inherited
表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解
2、 注解声明
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnnotation {
String name() default "张三";
String sex();
int age();
}
3、注解的使用
@MyAnnotation(name = "李四",sex = "男",age = 19)
public class Student {
public String name;
public String sex;
public Integer age;
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
4、注解的解析
public class Test {
public static void main(String[] args) throws Exception{
//获取属性类信息
Class studentClass=Student.class;
//判断是否添加注解
if(studentClass.isAnnotationPresent(MyAnnotation.class)){
//获取注解信息
MyAnnotation annotation = (MyAnnotation) studentClass.getAnnotation(MyAnnotation.class);
//创建对象
Student student = (Student) studentClass.getConstructor().newInstance();
//获取对象属性数组
Field[] fields = studentClass.getDeclaredFields();
for(Field field:fields){
//禁用访问安全检查
field.setAccessible(true);
//获取注解类对象并获取注解属性
Method method = annotation.getClass().getMethod(field.getName());
//获取注解属性的值
Object value = method.invoke(annotation);
//给注解属性赋值
field.set(student,value);
}
System.out.println(student.toString());
}else{
System.out.println("没有该注解");
}
}
}