
内容导航:
- 前言
- 1、java.lang.annotation.Retention接口
- 2、java.lang.annotation.AnnotatedElement接口
- 3、获取注解和元素值
1、java.lang.annotation.Retention接口
java.lang.annotation.Retention
接口指定带注解类型的注解要保留多长时间。
我们要在定义注解时指定java注解保留策略为运行时RUNTIME,运行时注入到字节码文件里,这样才可以在运行时反射并获取它。
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
//元素列表
}
2、java.lang.annotation.AnnotatedElement接口
表示当前在此VM中运行的程序的注释元素。这个接口允许以反射方式读取注释。此接口中方法返回的所有注释都是不可变的和可序列化的。调用方可以修改此接口的方法返回的数组,而不影响返回给其他调用方的数组。
直接子类: AccessibleObject, Class, Constructor, Executable, Field, Method, Package, Parameter
3、获取注解和元素值
Class<MyClass> class1 = MyClass.class;
// 第一种方式
MyAnnotation myAnnotation = (MyAnnotation) class1.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation);
System.out.println(myAnnotation.author());
// 第二种方式:
Annotation[] annotations = class1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 第三种方式
Annotation annotation = class1.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
持续更新,欢迎留言提议!
码字很累,多点赞多赞赏!

网友评论