Java Annotation and Reflection Principle Explanation

  • 2021-07-07 07:19:49
  • OfStack

1-point eye

If annotations want to play a greater role, they need the help of reflection mechanism. Through reflection, you can get the whole content of the annotation declared on a method.

1 There are two kinds of requirements:

1 Get all the annotations in the method, which is realized by calling getAnnotations.

2 Determine whether the operation is a specified annotation, which is realized by calling getAnnotation.

The following explains how to get these annotation information from the source code point of view.

2 source code guide-get all the annotations in the method


public class AccessibleObject implements AnnotatedElement {
  ...
  // Get all Annotation
  public Annotation[] getAnnotations() {
    return getDeclaredAnnotations();
  }  
  ...
}
public final class Method extends Executable {
  ...
  public Annotation[] getDeclaredAnnotations() {
    // Aim at Method Class, you need to call the parent class's getDeclaredAnnotations Method 
    return super.getDeclaredAnnotations();
  }  
  ...
}
//Method Parent class of Executable Adj. getDeclaredAnnotations Realize the acquisition of all annotation information 
public abstract class Executable extends AccessibleObject
  implements Member, GenericDeclaration {
  ...
  public Annotation[] getDeclaredAnnotations() {
    return AnnotationParser.toArray(declaredAnnotations());
  }  
  ...
}

3 source code guide-judge whether the operation is a specified annotation


public final class Method extends Executable {
  ...
  //// Get the specified Annotation
  public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    return super.getAnnotation(annotationClass);
  }
  ...
}
public abstract class Executable extends AccessibleObject
  implements Member, GenericDeclaration {
  ...
  public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    Objects.requireNonNull(annotationClass);
    // Gets information about the specified annotation class 
    return annotationClass.cast(declaredAnnotations().get(annotationClass));
  }  
  ...
}

Summarize


Related articles: