对注解概念不了解的可以先看这个:Java注解基础概念总结
前面有提到注解按生命周期来划分可分为3类:
1、RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
2、RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
3、RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
这3个生命周期分别对应于:Java源文件(.java文件) ---> .class文件 ---> 内存中的字节码。
那怎么来选择合适的注解生命周期呢?
首先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。
下面来介绍下运行时注解的简单运用。
获取注解
你需要通过反射来获取运行时注解,可以从 Package、Class、Field、Method...上面获取,基本方法都一样,几个常见的方法如下:
-
-
-
- public <A extends Annotation> A getAnnotation(Class<A> annotationType);
-
-
-
-
- public Annotation[] getAnnotations();
-
-
-
-
- public Annotation[] getDeclaredAnnotations();
-
-
-
-
- public boolean isAnnotationPresent(Class<? extends Annotation> annotationType);
-
-
-
-
- public Annotation[][] getParameterAnnotations();
要使用这些函数必须先通过反射获取到对应的元素:Class、Field、Method 等。
自定义注解
来看下自定义注解的简单使用方式,这里先定义3个运行时注解:
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.TYPE)
- public @interface ClassInfo {
- String value();
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.FIELD)
- public @interface FieldInfo {
- int[] value();
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- public @interface MethodInfo {
- String name() default "long";
- String data();
- int age() default 27;
- }
这3个注解分别适用于不同的元素,并都带有不同的属性,在使用注解是需要设置这些属性值。
再定义一个测试类来使用这些注解:
-
-
-
- @ClassInfo("Test Class")
- public class TestRuntimeAnnotation {
-
- @FieldInfo(value = {1, 2})
- public String fieldInfo = "FiledInfo";
-
- @FieldInfo(value = {10086})
- public int i = 100;
-
- @MethodInfo(name = "BlueBird", data = "Big")
- public static String getMethodInfo() {
- return TestRuntimeAnnotation.class.getSimpleName();
- }
- }
使用还是很简单的,最后来看怎么在代码中获取注解信息:
-
-
-
- private void _testRuntimeAnnotation() {
- StringBuffer sb = new StringBuffer();
- Class<?> cls = TestRuntimeAnnotation.class;
- Constructor<?>[] constructors = cls.getConstructors();
-
- sb.append("Class注解:").append("\n");
- ClassInfo classInfo = cls.getAnnotation(ClassInfo.class);
- if (classInfo != null) {
- sb.append(Modifier.toString(cls.getModifiers())).append(" ")
- .append(cls.getSimpleName()).append("\n");
- sb.append("注解值: ").append(classInfo.value()).append("\n\n");
- }
-
- sb.append("Field注解:").append("\n");
- Field[] fields = cls.getDeclaredFields();
- for (Field field : fields) {
- FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);
- if (fieldInfo != null) {
- sb.append(Modifier.toString(field.getModifiers())).append(" ")
- .append(field.getType().getSimpleName()).append(" ")
- .append(field.getName()).append("\n");
- sb.append("注解值: ").append(Arrays.toString(fieldInfo.value())).append("\n\n");
- }
- }
-
- sb.append("Method注解:").append("\n");
- Method[] methods = cls.getDeclaredMethods();
- for (Method method : methods) {
- MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);
- if (methodInfo != null) {
- sb.append(Modifier.toString(method.getModifiers())).append(" ")
- .append(method.getReturnType().getSimpleName()).append(" ")
- .append(method.getName()).append("\n");
- sb.append("注解值: ").append("\n");
- sb.append("name: ").append(methodInfo.name()).append("\n");
- sb.append("data: ").append(methodInfo.data()).append("\n");
- sb.append("age: ").append(methodInfo.age()).append("\n");
- }
- }
-
- System.out.print(sb.toString());
- }
所做的操作都是通过反射获取对应元素,再获取元素上面的注解,最后得到注解的属性值。
看一下输出情况,这里我直接显示在手机上:
这个自定义运行时注解是很简单的例子,有很多优秀的开源项目都有使用运行时注解来处理问题,有兴趣可以找一些来研究。因为涉及到反射,所以运行时注解的效率多少会受到影响,现在很多的开源项目使用的是编译时注解,关于编译时注解后面再来详细介绍。
相关内容:自定义注解之源码注解(RetentionPolicy.SOURCE)
分享到:
相关推荐
@Retention(RetentionPolicy.RUNTIME ) SOURCE 给编译器看的# 源码存在,字节码不存在 CLASS 给虚拟机的类加载器看的,#源码,.class存在, RUNTIME 用于反射 #源码,.class 字节码 存在 @Documented 这个注解可以...
* 使用`@Retention`指定注解的生命周期,例如:`@Retention(RetentionPolicy.RUNTIME)` * 使用`@Documented`指定注解应该被文档化,例如:`@Documented` * 使用`@Inherited`指定注解是否可以被继承,例如:`@...
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface KthLog { String value() default ""; } ``` 使用自定义注解 然后,我们可以把这个注解添加到需要记录日志的方法上。例如,...
RetentionPolicy.RUNTIME:注解被保留在编译后的字节码文件中,并且在运行时可通过反射访问。 @Target:这个元注解用于指定被注解的注解可以应用于哪些元素。它有一个ElementType数组类型的属性value,可以包含以下...
* RetentionPolicy.RUNTIME:注解在运行时也保留,并可以被反射机制读取。 @Retention 的作用是指定注解在哪个阶段被保留,例如在源代码中、在字节码中或在运行时。 2.@Target @Target 用于指定注解可以应用于...
+ RetentionPolicy.RUNTIME:指定注解可以保留在程序运行期间 * `@Target`:说明该注解可以被声明在哪些元素前 + ElementType.TYPE:说明该注解只能被声明在一个类前 + ElementType.FIELD:说明该注解只能被声明...
* `RetentionPolicy.RUNTIME`:指定注解可以保留在程序运行期间。 2. `@Target`:它是被定义在一个注解类的前面,用来说明该注解可以被声明在哪些元素前。它有以下参数: * `ElementType.TYPE`:说明该注解只能被...
3. @Retention(RetentionPolicy.RUNTIME):该注解用于指定注解的保留策略为RetentionPolicy.RUNTIME,即该注解将被保留到运行时。 4. 反射机制的应用:反射机制可以应用于实际的测试中,以便更好地测试程序的正确性...
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Environment { String value(); } @Environment("beijing") @Component public class DemoServiceBeijing implements ...
RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们 annotation实际上就是一个标签,单独存在的时候没有任何实际意义。为了便于理解,这里再延伸一下...
利用spring如何实现接口限流 ...@Retention(RetentionPolicy.RUNTIME) public @interface AccessLimit { //限流唯一标识 String key() default ""; //限流时间 int time(); //限流次数 int count(); }
一、注解和反射 @Target...Retention 保留级别SOURCE: 注解会被保留在源码级别,会被编译器忽略CLASS :注解会被保留在字节码级别,会被编译器保留,但会被JVM忽略RUNTIME: 注解会在运行时保留,由JVM保留,因此可以
@Retention(RetentionPolicy.RUNTIME) @Documented public @interface NoRepeatSubmitAnnotation { } ``` 切面处理类: ```java @Aspect @Component @Order(0) public class NoRepeatSubmitAspect { @Autowired ...
@Retention(RetentionPolicy.RUNTIME) //定义声明周期 public @interface Column { String value(); } 注解的作用范围@Target 和 生命周期 @Retention 作用范围:包,类,字段,方法,方法的参数,局部变量 生命...
@Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = ...
@Retention(RetentionPolicy.RUNTIME) //在运行是加载Annotation到JVM中 public @interface MyAnnotation { public String value() default "yellow"; public int[] array() default {1,2}; public Meta...
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FunctionalInterface {} JDK1.8常用函数式接口 函数式接口 参数类型 返回类型 抽象方法名 描述 其他方法 Rnnnable 无
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface CacheNameRemove { String name(); String[] keys() default {}; } //根据key值来移除基于...