Literacy on generics, reflection and annotation in Java

Java for the rest of my life 2020-11-08 12:12:31
literacy generics reflection annotation java


Generic

Generic concept

Generics are in JDK1.5 And then introduced , It aims to make us write more general , More flexible code . The universal means are to parameterize data types , When defining generics , The corresponding data type is uncertain , When a generic method is called , Will specify the specific type , The core goal is to solve the problem of container type security check at compile time .

Generic : It is generally used in class 、 Method 、 Interface , It's called generic class 、 Generic interface 、 Generic methods

The use of generics

 package demo.generic;
import lombok.Data;
/**
* Definition of a generic class
* @param <T>
*/
@Data
public class GenericClassExample<T> {
//member The type of this member variable is T,T The type of is specified externally
private T member;
// The constructor parameter of a generic class member The type of is also T,T The type of is specified externally
public GenericClassExample(T member) {
this.member = member;
}
// Common methods can also be defined in generic classes , The parameters of ordinary methods are also generic
public T handleSomething(T target) {
return target;
}
}
  1. Generic parameters do not support basic types ; Information about generics doesn't go into the runtime phase
     package demo.generic;
    public class GenericDemo {
    public static void main(String[] args) {
    GenericClassExample<String> strExample = new GenericClassExample<>("abc");
    GenericClassExample<Integer> intExample = new GenericClassExample<>(123);
    System.out.println(strExample.getClass()); // Print the type of a generic class
    System.out.println(intExample.getClass()); // Print the type of a generic class
    }
    }
    // ********** Running results *********
    //class demo.generic.GenericClassExample
    //class demo.generic.GenericClassExample
    // We can see from the running results that strExample and intExample Of the same type , Therefore, type constraints for generic classes are only valid at compile time
    
  2. Whether the class with inheritance relationship can be used in generics ?
    • Use wildcards ?, But it makes generic type checking meaningless
    • Add boundaries to generics <? extends E>
    • Add lower bounds to generics <? super E>
      package demo.generic;
      public class GenericDemo {
      // Add the above boundary to generics ? extends E, The generic type must be E Of or its subclass
      public static void handleMember(GenericClassExample<? extends Number> integerExample) {
      Integer result = (Integer) integerExample.getMember() + 100;
      System.out.println("result is " + result);
      }
      // Add lower bounds to generics ? super E , The generic type must be E Of or its parent class
      public static void handleSuperMember(GenericClassExample<? super Integer> integerExample) {
      Integer result = (Integer) integerExample.getMember() + 100;
      System.out.println("result is " + result);
      }
      public static void main(String[] args) {
      GenericClassExample<String> strExample = new GenericClassExample<>("abc");
      GenericClassExample<Integer> integerExample = new GenericClassExample<>(123);
      GenericClassExample<Number> numberExample = new GenericClassExample<>(new Integer(123));
      // handleMember(strExample); // Error will be reported in compilation , because String No Number Subclasses of
      handleMember(integerExample); // No mistake. , because Integer yes Number Subclasses of
      handleSuperMember(integerExample); // No mistake. , because Integer The same type as a generic class
      handleSuperMember(numberExample ); // No mistake. , because Number It's a generic class Integer Parent class of
      }
      }
      
  3. Generic methods : Methods identified using generic identifiers
    // <E> Generic identifier
    public static <E> void printArray(E[] array) {
    for(E element : array){
    System.out.printf("%s",element);
    }
    }
    
  4. The meaning of generic letters
    • E - Element: Use... In a collection , Because there are elements in the collection
    • T - Type: Java class
    • K - Key: key
    • V - Value: value
    • N - Number: value type

Reflection

The concept and function of reflection

Reflection allows the program to self check at runtime and to operate on internal members . Reflection mainly means that the program can access 、 The ability to detect and modify its own state or behavior , And according to the state and result of their own behavior , Adjust or modify the state and related semantics of the behavior described by the application .

  1. The role of the reflex mechanism
    • At run time, determine the class that any object belongs to
    • Get the object of the class at run time
    • Access at runtime java Object properties 、 Method 、 Construction method, etc
  2. java.lang.reflect The main classes in the class library
    • Field: Represents a member variable in a class
    • Method: Represents a method in a class
    • Constructor: Represents the constructor of a class
    • Array: This class provides a static method for dynamically creating arrays and accessing array elements
  3. Reflection depends on Class: The corresponding class used to represent the runtime type information
    • Each class has a unique corresponding Class object
    • Class Class is class type , and Class The object is of class type
    • Class Class characteristics
      • Class Class is also a kind of class ,class Is the keyword
      • Class Class has only one private constructor , Only JVM Be able to create Class Class
      • JVM There is only one corresponding to a class in Class Object to describe its type information
    • obtain CLass Three ways of objects
      • Object -> getClass()
      • Any data type ( Including basic data types ) There is one. “ static state ” Of class attribute
      • adopt Class Class static methods :forName(String className) ( Commonly used )
         package demo.reflect;
        public class ReflectTarget {
        public static void main(String[] args) throws ClassNotFoundException {
        // The first way to get Class object
        ReflectTarget reflectTarget = new ReflectTarget();
        Class reflectClass01 = reflectTarget.getClass();
        System.out.println("1st: " + reflectClass01);
        // Get... In the second way Class object
        Class reflectClass02 = ReflectTarget.class;
        System.out.println("2nd: " + reflectClass01);
        // Compare the first way to get class Object and the second way to get class Whether the object is the same
        System.out.println(reflectClass01 == reflectClass02);
        // The third way to get Class object
        Class reflectClass03 = Class.forName("demo.reflect.ReflectTarget");
        System.out.println("3rd: " + reflectClass03);
        // Compare the second way to get class Object and the third way to get class Whether the object is the same
        System.out.println(reflectClass02 == reflectClass03);
        }
        }
        /************ The operation results are as follows ************/
        /*
        * 1st: class demo.reflect.ReflectTarget
        * 2nd: class demo.reflect.ReflectTarget
        * true
        * 3rd: class demo.reflect.ReflectTarget
        * true
        * */
        /**
        * According to the operation results, we know that :Class There is only one object
        * **/
        ```
        
      • Class The object is like a mirror , Through this mirror you can see the structure of the class

The main use of reflection

  • How to get the constructor of a class and use
    • Customized on our top ReflectTarget Class to create various types of constructors , Used for testing
       // -------- Constructors --------
      // The access modifier is the default constructor , That is, the same package can be accessed
      ReflectTarget(String str) {
      System.out.println("( Default ) Construction method of s= " + str);
      }
      // Parameter free constructor
      public ReflectTarget() {
      System.out.println(" A public nonparametric constructor was called ...");
      }
      // A constructor with one parameter
      public ReflectTarget(char name) {
      System.out.println(" Called a constructor with a parameter , Parameter is :" + name);
      }
      // Constructors with multiple arguments
      public ReflectTarget(String name,int index) {
      System.out.println(" Called constructor with multiple arguments , Parameter values for 【 Target name 】:" + name + "【 Serial number 】" + index);
      }
      // Protected constructors
      protected ReflectTarget(boolean b) {
      System.out.println(" Protected construction methods :" + b);
      }
      // Private constructor
      private ReflectTarget(int index){
      System.out.println(" Private construction method , Serial number :" + index);
      }
      
    • Create a new class ConstructorCollector Test all construction methods of getting target reflection class by reflection
       package demo.reflect;
      import java.lang.reflect.Constructor;
      import java.lang.reflect.InvocationTargetException;
      /**
      * Get construction method :
      * 1) Batch construction method
      * public Constructor[] getConstructors() Get all ” public “ Construction method
      * public Constructor[] getDeclaredConstructors() Get all the construction methods ( Including private 、 The protected 、 Default and public )
      * 2) Get a single method , And call
      * public Constructor getConstructor(Class...parameterTypes) Get a single ” public “ Construction method
      * public Constructor getDeclaredConstructor(Class...parameterTypes) Get a constructor ( It can be private 、 The protected 、 Default and public )
      *
      * Call constructor : Constructor --> newInstance(Object...intArgs)
      */
      public class ConstructorCollector {
      public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
      Class clazz = Class.forName("demo.reflect.ReflectTarget");
      // Get all the public constructors
      System.out.println("************** All public constructors **************");
      Constructor[] conArray = clazz.getConstructors();
      for (Constructor con : conArray) {
      System.out.println(con);
      }
      // Get all the construction methods
      System.out.println("************** All the construction methods ( Including private 、 The protected 、 Default and public )**************");
      conArray = clazz.getDeclaredConstructors();
      for (Constructor con : conArray) {
      System.out.println(con);
      }
      // Or get a single public constructor with parameters
      System.out.println("************** Get public 、 A construction method with two parameters **************");
      Constructor con = clazz.getConstructor(String.class,int.class);
      System.out.println("con = " + con);
      // Get a single private constructor
      System.out.println("************** Get a single private constructor **************");
      con = clazz.getDeclaredConstructor(int.class);
      System.out.println("con = " + con);
      System.out.println("##################################################");
      System.out.println("************** Create an instance through a private constructor **************");
      con.setAccessible(true); // Set up violent visits , Ignore access modifiers
      ReflectTarget reflectTarget = (ReflectTarget) con.newInstance(1);
      }
      }
      /***
      * The operation results are as follows :
      * ************** All public constructors **************
      * public demo.reflect.ReflectTarget(java.lang.String,int)
      * public demo.reflect.ReflectTarget()
      * public demo.reflect.ReflectTarget(char)
      * ************** All the construction methods ( Including private 、 The protected 、 Default and public )**************
      * private demo.reflect.ReflectTarget(int)
      * protected demo.reflect.ReflectTarget(boolean)
      * public demo.reflect.ReflectTarget(java.lang.String,int)
      * demo.reflect.ReflectTarget(java.lang.String)
      * public demo.reflect.ReflectTarget()
      * public demo.reflect.ReflectTarget(char)
      * ************** Get public 、 A construction method with two parameters **************
      * con = public demo.reflect.ReflectTarget(java.lang.String,int)
      * ************** Get a single private constructor **************
      * con = private demo.reflect.ReflectTarget(int)
      * ##################################################
      * ************** Create an instance through a private constructor **************
      * Private construction method , Serial number :1
      */
      
  • How to get the field of a class and use
    • Customized on our top ReflectTarget Create various fields in class that access modifier modifiers modify , Used for testing
       // -------- Field --------
      public String name;
      protected int index;
      char type;
      private String targetInfo;
      @Override
      public String toString() {
      return "ReflectTarget{" +
      "name='" + name + '\'' +
      ", index=" + index +
      ", type=" + type +
      ", targetInfo='" + targetInfo+ '\'' +
      '}';
      }
      
    • Create a new class FieldCollector The test gets all member variables of the target reflection class through reflection
       package demo.reflect;
      import java.lang.reflect.Field;
      import java.lang.reflect.InvocationTargetException;
      /**
      * Get the member variable and call :
      * 1) In bulk
      * Field[] getFields() Get all ” Public field ”
      * Field[] getDeclaredFields() Get all fields ( Including private 、 The protected 、 Default and public )
      * 2) Get a single
      * public Field getField(String fieldName) Get a single ” public “ Field
      * public Field getDeclaredField(String fieldName) Get a field ( It can be private 、 The protected 、 Default and public )
      *
      * Set field value : Field --> public void set(Object obj,Object value)
      * Parameter description :
      * 1. obj: The object corresponding to the field to be set
      * 2. value: The value to set for the field
      */
      public class FieldCollector {
      public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
      // obtain class object
      Class reflectTargetClass = Class.forName("demo.reflect.ReflectTarget");
      // Get all the public fields
      System.out.println("************** Get all the public fields **************");
      Field[] fieldArray = reflectTargetClass.getFields();
      for (Field field : fieldArray) {
      System.out.println(field);
      }
      // Get all fields
      System.out.println("************** Get all fields ( Including private 、 The protected 、 Default and public )**************");
      fieldArray = reflectTargetClass.getDeclaredFields();
      for (Field field : fieldArray) {
      System.out.println(field);
      }
      // Get public fields and assign values
      System.out.println("************** Get public fields and assign values **************");
      Field field = reflectTargetClass.getField("name");
      System.out.println(" Public fields name = " + field);
      // Call a parameterless constructor through reflection , And create an object using a nonparametric construct
      ReflectTarget reflectTarget = (ReflectTarget)reflectTargetClass.getConstructor().newInstance();
      // For getting objects field Attribute assignment
      field.set(reflectTarget," To reflect number one ");
      // Verify the corresponding value name
      System.out.println(" verification name: " + reflectTarget.name); // because name Property is public , So you can call... Directly through an instance
      System.out.println("************** Get private fields targetInfo And the assignment **************");
      field = reflectTargetClass.getDeclaredField("targetInfo");
      System.out.println(field);
      field.setAccessible(true); // Set up violent visits
      field.set(reflectTarget,"13730862985");
      // because targetInfo Property is private , You cannot call... Directly through an instance , Because we rewritten toString Method , So print directly reflectTarget Just be the object
      System.out.println(" verification targetInfo: " + reflectTarget);
      }
      }
      /**
      * The operation results are as follows :
      * ************** Get all the public fields **************
      * public java.lang.String demo.reflect.ReflectTarget.name
      * ************** Get all fields ( Including private 、 The protected 、 Default and public )**************
      * public java.lang.String demo.reflect.ReflectTarget.name
      * protected int demo.reflect.ReflectTarget.index
      * char demo.reflect.ReflectTarget.type
      * private java.lang.String demo.reflect.ReflectTarget.targetInfo
      * ************** Get public fields and assign values **************
      * Public fields name = public java.lang.String demo.reflect.ReflectTarget.name
      * A public nonparametric constructor was called ...
      * verification name: To reflect number one
      * ************** Get private fields targetInfo And the assignment **************
      * private java.lang.String demo.reflect.ReflectTarget.targetInfo
      * verification targetInfo: ReflectTarget{name=' To reflect number one ', index=0, type= , targetInfo='13730862985'}
      */
      
    • Be careful : adopt getField() Method can get the public fields inherited from the parent class , but getDeclareField() Method can't get fields inherited from the parent class
  • How to get the method of a class and call
    • Customized on us ReflectTarget Create methods in class that are decorated by various access modifiers , Used for testing
       package demo.reflect;
      import java.lang.reflect.InvocationTargetException;
      import java.lang.reflect.Method;
      /**
      * Get member methods and call :
      * 1) In bulk
      * public Method[] getMethods() Get all ” Public methods ”( Methods that contain the parent class , Also includes Object Public methods in class )
      * public Method[] getDeclaredMethods() Get all member methods ( Including private 、 The protected 、 Default and public )
      * 2) Get a single
      * public Method getMethod(String name,Class<?>...parameterTypes) Get a single ” public “ Field
      * Parameters :
      * name: Method name
      * Class...: Paramedic Class Type object
      * public Method getDeclaredMethod(String name,Class<?>...parameterTypes) Get a field ( It can be private 、 The protected 、 Default and public )
      *
      * Calling method :
      * Method --> public Object invoke(Object obj,Object...args);
      * Parameter description :
      * obj: The object to call the method method
      * args: The argument passed when the method is called
      */
      public class MethodCollector {
      public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
      // obtain class object
      Class reflectTargetClass = Class.forName("demo.reflect.ReflectTarget");
      // Get all the public methods
      System.out.println("******************* Get all public Method , Include parent and Object*******************");
      Method[] methodArray = reflectTargetClass.getMethods();
      for (Method method : methodArray) {
      System.out.println(method);
      }
      // Get all the methods of this class
      System.out.println("******************* Get all the methods of this class , Including private *******************");
      methodArray = reflectTargetClass.getDeclaredMethods();
      for (Method method : methodArray) {
      System.out.println(method);
      }
      // Get a single public method
      System.out.println("******************* To obtain public ownership show1()*******************");
      Method method = reflectTargetClass.getMethod("show1", String.class);
      System.out.println(method);
      // Call a parameterless constructor through reflection , And create an object using a nonparametric construct
      ReflectTarget reflectTarget = (ReflectTarget)reflectTargetClass.getConstructor().newInstance();
      method.invoke(reflectTarget," Method 1 to be reflected ");
      System.out.println("******************* Get private show4()*******************");
      method = reflectTargetClass.getDeclaredMethod("show4", int.class);
      System.out.println(method);
      method.setAccessible(true);
      // Accept show4() The return value of
      String result = String.valueOf(method.invoke(reflectTarget, 100)) ;
      System.out.println(result);
      }
      }
      /**
      * The operation results are as follows : We can see from the running results that getMethods(), Get Object Public methods in class
      * ******************* Get all public Method , Include parent and Object*******************
      * public static void demo.reflect.ReflectTarget.main(java.lang.String[]) throws java.lang.ClassNotFoundException
      * public java.lang.String demo.reflect.ReflectTarget.toString()
      * public void demo.reflect.ReflectTarget.show1(java.lang.String)
      * public final void java.lang.Object.wait() throws java.lang.InterruptedException
      * public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
      * public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
      * public boolean java.lang.Object.equals(java.lang.Object)
      * public native int java.lang.Object.hashCode()
      * public final native java.lang.Class java.lang.Object.getClass()
      * public final native void java.lang.Object.notify()
      * public final native void java.lang.Object.notifyAll()
      * ******************* Get all the methods of this class , Including private *******************
      * public static void demo.reflect.ReflectTarget.main(java.lang.String[]) throws java.lang.ClassNotFoundException
      * public java.lang.String demo.reflect.ReflectTarget.toString()
      * public void demo.reflect.ReflectTarget.show1(java.lang.String)
      * private java.lang.String demo.reflect.ReflectTarget.show4(int)
      * protected void demo.reflect.ReflectTarget.show2()
      * void demo.reflect.ReflectTarget.show3()
      * ******************* To obtain public ownership show1()*******************
      * public void demo.reflect.ReflectTarget.show1(java.lang.String)
      * A public nonparametric constructor was called ...
      * Public is called ,String Parametric show1(): str = Method 1 to be reflected
      * ******************* Get private show4()*******************
      * private java.lang.String demo.reflect.ReflectTarget.show4(int)
      * Private called , And it has a return value of ,int Parametric show4(): index = 100
      * show4Result
      */
      

annotation

Introduction and function of notes

Because reflection needs to get the full name of the relevant class ( Class name + Package name ), So we also need to record which classes are obtained by reflection . We can go through XML To save class related information for reflection , Besides , We can also save class related information through annotations for reflection calls .
annotation : Provides a way to set metadata for program elements

  • Metadata is added to program elements such as methods 、 Field 、 Extra information on classes and packages
  • Annotation is a decentralized way to set metadata ,XML It's a centralized setting
  • Annotations can't interfere with the program directly
  • Instructions for decompiling bytecode files :javap -verbose com.reminis.demo.annotation.TestAnnotation, We can see that our custom annotations are automatically inherited by decompilation Annotation
  • The function of annotation
    • As a specific marker , Used to tell the compiler some information
    • Dynamic processing at compile time , Such as dynamically generating code
    • Run time dynamic processing , As a carrier of additional information , For example, get annotation information
  • Classification of annotations
    • Standard notes :Override、Deprecated、SuppressWarnings
    • Yuan notes :@Retention、@Target、@Inherited、@Documented, A comment used to modify an annotation , Usually used in the definition of annotation
      • @Target: The purpose of the annotations , Describe the scope of the modified annotation
        • packages、types( class 、 Interface 、 enumeration 、Annotation type )
        • Type members ( Method 、 Construction method 、 Member variables 、 Enumerated values )
        • Method parameters and local variables ( Like loop variables 、catch Parameters )
      • @Retention: Lifecycle of annotations ( Note the length of time the annotation is retained )
      • @Documented: Whether annotations should be included in JavaDoc In the document
      • @Inherited: Whether subclasses are allowed to inherit the annotation

Implementation of custom annotation

Custom annotations automatically implement java.lang.annotation.Annotation

 public @interface Annotation name {
Modifier Return value Property name () The default value is ;
Modifier Return value Property name () The default value is ;
...
}

Types supported by annotation properties : All the basic types (int,float,boolean,byte,double,char,long,short)、 String type 、 Class type 、Enum type 、Annotation type 、 All the above types of arrays .
We now customize an annotation PersonInfoAnnotation, Can be used in fields , Valid when the program is running , as follows :

package demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Custom annotation
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonInfoAnnotation {
// name
public String name();
// Age
public int age() default 19;
// Gender
public String gender() default " male ";
// development language
public String[] language();
}

Let's also define a custom annotation CourseInfoAnnotation, This annotation can be used on classes and methods , Valid when the program is running , as follows :

package demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CourseInfoAnnotation {
// Course name
public String courseName();
// Course label
public String courseTag();
// Course introduction
public String courseProfile();
// Course code
public int courseIndex() default 107;
}

Create a new SelfStudyCourse class , On this class and its fields and methods , Use our defined annotations above

package demo.annotation;
@CourseInfoAnnotation(courseName = " computer network ",courseTag = " Fundamentals of computer ",
courseProfile = " The core content of computer network learning is the learning of network protocol ." +
" Network protocol is a rule established for data exchange in computer network 、 Standards, or a collection of conventions ." +
" Because the character sets that different users' data terminals may take are different , The two need to communicate , It has to be done on a certain standard ")
public class SelfStudyCourse {
@PersonInfoAnnotation(name = " New one ",language = {"Java","C++","Go","Python"})
public String author;
@CourseInfoAnnotation(courseName = "Linux course ",courseTag = " Programming based ",
courseProfile = "Linux follow GNU General public permit (GPL), Any individual or organization can use it freely Linux All underlying source code for , You can also freely modify and republish ." +
" because Linux It's free software , Anyone can create a fit for their needs Linux Distribution version ",courseIndex = 208)
public void getCourseInfo(){
}
}

Create test class AnnotationDemo, Call the method of the class that uses the custom annotation above , View the run information

package demo.annotation;
public class AnnotationDemo {
public static void main(String[] args) {
SelfStudyCourse selfStudyCourse = new SelfStudyCourse();
selfStudyCourse.getCourseInfo();
System.out.println("finish");
}
}
/**
* Running results :
* finish
* According to the running results, we can see , If you don't handle annotations in a program , It is consistent with the output without annotation ,
* */

If we don't deal with annotations , There's no difference between that and not , So how do we get the information from the annotations ? Through the reflection mentioned above , Let's look at some of the main classes involved in reflection (Field,Method,Constructor,Class) Source code can know , These reflection related classes implement AnnotatedElement Interface , We did this by looking at AnnotatedElement Interface source code , The following methods are commonly used :

  • Annotation[] getAnnotations(); // Used to get all annotations on an object , Including inherited
  • T getAnnotation(Class annotationClass); // Gets a single specified annotation on an object
  • boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); // Used to determine whether there is a specified annotation

Now we get information on class annotations by reflection , The code implementation is as follows :

package demo.annotation;
import java.lang.annotation.Annotation;
public class AnnotationParse {
// Parse the comments above the class
public static void parseTypeAnnotation() throws ClassNotFoundException {
Class<?> clazz = Class.forName("demo.annotation.SelfStudyCourse");
// What we get here is class Object annotation , Instead of the annotations of the methods and member variables in it
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
CourseInfoAnnotation courseInfoAnnotation = (CourseInfoAnnotation) annotation;
System.out.println(" Course name : " +courseInfoAnnotation.courseName() + "\n" +
" Course labels : " + courseInfoAnnotation.courseTag() + "\n" +
" Course introduction : "+ courseInfoAnnotation.courseProfile() + "\n" +
" Course code : " + courseInfoAnnotation.courseIndex());
}
}
public static void main(String[] args) throws ClassNotFoundException {
parseTypeAnnotation();
}
}
/**
* The program runs as follows :
* Course name : computer network
* Course labels : Fundamentals of computer
* Course introduction : The core content of computer network learning is the learning of network protocol . Network protocol is a rule established for data exchange in computer network 、 Standards, or a collection of conventions . Because the character sets that different users' data terminals may take are different , The two need to communicate , It has to be done on a certain standard
* Course code : 107
*/

Now, we can get annotation information on member variables and methods by reflection

 // Parse the annotation information on the field
public static void parseFieldAnnotation() throws ClassNotFoundException {
Class<?> clazz = Class.forName("demo.annotation.SelfStudyCourse");
// Get all the member variables of the object
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// Determine whether there is a comment of the specified annotation type in the member variable
boolean hasAnnotation = field.isAnnotationPresent(PersonInfoAnnotation.class);
if (hasAnnotation) {
PersonInfoAnnotation personInfoAnnotation = field.getAnnotation(PersonInfoAnnotation.class);
System.out.println(" name : " + personInfoAnnotation.name() + "\n" +
" Age : " + personInfoAnnotation.age() + "\n" +
" Gender : " + personInfoAnnotation.gender());
for (String language : personInfoAnnotation.language()) {
System.out.println(" Course name : " + language);
}
}
}
}
// Annotation information on parsing methods
public static void parseMethodAnnotation() throws ClassNotFoundException {
Class<?> clazz = Class.forName("demo.annotation.SelfStudyCourse");
// Get all the member variables of the object
Method[] methods = clazz.getMethods();
for (Method method : methods) {
// Determine whether there are annotations of the specified annotation type in the method
boolean hasAnnotation = method.isAnnotationPresent(CourseInfoAnnotation.class);
if (hasAnnotation) {
CourseInfoAnnotation methodAnnotation = method.getAnnotation(CourseInfoAnnotation.class);
System.out.println(" Course name : " +methodAnnotation.courseName() + "\n" +
" Course labels : " + methodAnnotation.courseTag() + "\n" +
" Course introduction : "+ methodAnnotation.courseProfile() + "\n" +
" Course code : " + methodAnnotation.courseIndex());
}
}
}

Annotation to get the underlying implementation of attribute values , It's through JVM Generate proxy objects for annotations .

How annotations work

  • Assign values to annotation properties in the form of key value pairs
  • The compiler checks the scope of annotations , Write the annotation information to the element attribute table ,
  • Runtime JVM take RUNTIME All annotation attributes are extracted and finally saved map in
  • establish AnnotationInvocationHandler Instance and pass in the previous map in
  • JVM Use JDK Dynamic proxy generates proxy classes for annotations , And initialize the corresponding processor (AnnotationInvocationHandler)
  • call invoke Method , Return the attribute value corresponding to the annotation by passing in the method name
版权声明
本文为[Java for the rest of my life]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云