1. RetentionPolicy.SOURCE: The annotation is only retained in the source file. When the Java file is compiled into a class file, the annotation is abandoned;
2. RetentionPolicy.CLASS: The annotation is retained to the class file, but is abandoned when jvm loads the class file. This is the default life cycle;
3. RetentionPolicy.RUNTIME: The annotation is not only saved to the class file, but still exists after jvm loads the class file;
These three life cycles correspond to: Java source file (.java file)--->.class file----> bytecode in memory.
So how do you choose the right annotation life cycle?
First of all, we must clarify the life cycle length SOURCE<CLASS<RUNTIME, so where the former can act, the latter can act. Generally, if you need to dynamically obtain annotation information at runtime, you can only use RUNTIME annotation; if you want to perform some preprocessing operations at compile time, such as generating some auxiliary code (such as ButterKnife), you can use CLASS annotation; if you only do some checking operations, such as @Override and @SuppressWarnings, you can use SOURCE annotation.
The following is a simple application of runtime annotations.
Get annotation
You need to obtain runtime annotations through reflection, which can be obtained from Package, Class, Field, Method.... The basic methods are the same. Several common methods are as follows:
/** * Get annotation of the specified type*/public <A extends Annotation> A getAnnotation(Class<A> annotationType);/** * Get all annotations, if any*/public Annotation[] getAnnotations();/** * Get all annotations, ignore inherited annotations*/public Annotation[] getDeclaredAnnotations();/** * Specify whether the annotation exists on this element, return true if there is, otherwise false */public Boolean isAnnotationPresent(Class<? extends Annotation> annotationType);/** * Get all annotations for parameters in the Method*/public Annotation[][] getParameterAnnotations();
To use these functions, you must first obtain the corresponding elements through reflection: Class, Field, Method, etc.
Custom annotations
Let’s take a look at the simple way to use custom annotations. Here we first define 3 runtime annotations:
// Applicable class, interface (including annotation type) or enum @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ClassInfo { String value(); } // Applicable field attributes, also include enum constants @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldInfo { int[] value(); } // Applicable method @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodInfo { String name() default "long"; String data(); int age() default 27; }These three annotations are applicable to different elements and all have different attributes. When using annotations, you need to set these attribute values.
Define another test class to use these annotations:
/** * Test runtime annotation*/@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();}}It is still very simple to use. Finally, let’s see how to get annotation information in the code:
/** * Test runtime annotation*/private void _testRuntimeAnnotation() {StringBuffer sb = new StringBuffer();Class<?> cls = TestRuntimeAnnotation.class;Constructor<?>[] constructors = cls.getConstructors();// Get the annotation of the specified type sb.append("Class annotation: ").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("Annotation value: ").append(classInfo.value()).append("/n/n");}sb.append("Field annotation: ").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("Annotation value: ").append(Arrays.toString(fieldInfo.value())).append("/n/n");}}sb.append("Method annotation: ").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("Annotation value: ").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());}The operations are done to obtain the corresponding element through reflection, then obtain the annotation on the element, and finally obtain the attribute value of the annotation.
Let’s take a look at the output, here I will directly display it on my phone:
Summarize
The above is all the detailed explanation of the basic concepts of Java language annotation, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!