Java learning notes annotation and reflection, Class class, Class loader, Java Memory Analysis

Keywords: Java JDK jvm Programming

annotation

  • Annotation is a technology introduced from JDK 5.0

  • The role of Annotation:

    • It's not the program itself, it can explain the program (it's no different from comment)
    • Can be read by other programs (such as compilers)
  • Annotation format

    • Annotation exists in "@ annotation name" code, and some parameter values can be added

      	@SuppressWarnings(value="unchecked").
      
  • Annotations can be attached to package, class, method, field, etc., which is equivalent to adding additional auxiliary information to them. We can access these metadata through reflection mechanism programming

Built in annotation

  • @Override: defined in java.lang.Override This comment only applies to decorated methods, indicating that a method declaration intends to override another method in a superclass.

  • @Deprecated: defined in java.lang.Deprecated This annotation can be used to decorate methods, properties, classes, indicating that programmers are not encouraged to use such elements, usually because it is dangerous or there are better choices

  • @Supplesswarnings: definition again java.lang.SuppressWarnings Different from the strong two comments, you need to add a parameter to use correctly. These parameters have been defined. We only need to use them selectively

    @SuppressWarnnings("all")
    @Suppresswarnnings("unchecked")
    @Suppresswarnnings("unchecked","deprecation")
    
  • package Annotation;
    import java.util.ArrayList;
    import java.util.List;
    @SuppressWarnings("all")
    public class test01 extends Object{
        @Override
        public String toString() {
            return super.toString();
        }
        @Deprecated
        public static void test(){
            System.out.println("Deprecated");
        }
        public void  test02(){
            List list=new ArrayList();
        }
    
        public static void main(String[] args) {
            test();//There will be a dash
        }
    }
    
  • Meta annotation and custom annotation

  • Meta annotation is responsible for interpreting other annotations. java defines four standard meta annotation types, which are used to provide explanations for other annotation types.

  • These types and their wisdom teeth java.lang.annotation Found in package

    • Target: indicates where our annotation can be used

    • Retention: indicates where our annotation is still valid

      runtime>class>sources
    • Documented: indicates whether to generate our annotations into JAVAdoc

    • Inherited: the annotations of the subclass that can inherit the parent are all

      package Annotation;
      import java.lang.annotation.*;
      public class test02 {
          @MyAnnotation
          public void test(){
          }
      }
      @Target(value={ElementType.METHOD,ElementType.TYPE})//Indicates that the annotation can be used in classes and methods
      @Retention(value = RetentionPolicy.RUNTIME)//Indicates that the annotation is still valid at run time (for the widest range, it can also be / / in class and sources)
      @Documented//Indicates that our annotations can be generated in Javadoc
      @Inherited//Annotation indicating that the child class can inherit the parent class
      @interface MyAnnotation{
      }
      
  • When using @ interface custom annotation, it automatically inherits java.lang.annotation.Annotation interface

    • @Interface is used to declare an annotation. Format: (Public) @ interface annotation name {definition content}
    • Each of these methods actually declares a configuration parameter
    • The name of the method is the name of the parameter
    • Return value type is the type of parameter (return value type can only be basic type, Class, String, enum)
    • You can declare the default value of the parameter through default
    • If there is only one parameter member, the general parameter name is value
    • Annotation element metaphor Yao Youzhi, when we define annotation, we often use empty string, 0 as the default value
    package Annotation;
    import java.lang.annotation.*;
    public class test02 {
        @MyAnnotation1(age=18,name="tom")//Annotation can display assignment. If there is no default value, we must assign annotation. If there is default value, we can omit it
        public void test1(){
        }
        @MyAnnotation2("xxx")//If there is only one parameter member, the parameter name is generally set to value. In this case, write the parameter value directly when calling
        public void test2(){
        }
    }
    @Target(value={ElementType.METHOD,ElementType.TYPE})//Indicates that the annotation can be used in classes and methods
    @Retention(value = RetentionPolicy.RUNTIME)//Indicates that the annotation is still valid at run time (for the widest range, it can also be / / in class and sources)
    @Documented//Indicates that our annotations can be generated in Javadoc
    @Inherited//Annotation indicating that the child class can inherit the parent class
    @interface MyAnnotation1{
        //Parameter of annotation: parameter type + parameter name ()
        String name() default "";
        int age();
        int id() default -1;//Default is used to declare the default value of the parameter
    }
    @interface MyAnnotation2{
        String value();
    }
    

reflex

Static language and dynamic language

  • Dynamic language: it is a kind of language that can change its structure at runtime: for example, new functions, objects and even codes can be introduced, existing functions can be deleted or other structural changes can be made. That is, at run time, the code can change its structure according to certain conditions
    • Object-C, C, JavaScript, PHP, Python, etc
  • Static language: a language whose runtime structure is immutable is static language. Such as Java, C, C++
  • Java is not a dynamic language, but it can be called "quasi dynamic language". That is to say, Java has a certain dynamic nature. We can use reflection mechanism to obtain features similar to dynamic languages. Java's dynamic nature makes programming more flexible.

Java reflection

  • In reflection, Java is regarded as the key of dynamic language. Reflection mechanism allows the program to obtain the internal information of any class with the help of Reflection API during execution, and can directly operate the internal properties and methods of any object.

  • After loading a Class, an object of Class type is generated in the method area of heap memory (a Class has only one Class object), which contains the complete Class structure information. We can see the structure of the Class through this object. This object is like a mirror, through which we can see the structure of the Class, so we call it reflection

    Normal method: import the required package class name - > instantiate via new - > get the instantiated object
    Reflection method: instantiate the object – > getclass() method – > get the complete package class name

function

  • Judge the class of any object at runtime
  • Construct an object of any class at run time
  • Judge the member variables and methods of any class at runtime
  • Get generic information at run time
  • Calling member variables and methods of an object at run time
  • Processing annotations at run time
  • Generate dynamic agent
  • ...

Advantages and disadvantages

  • Advantages: it can dynamically create objects and compile, reflecting great flexibility
  • Disadvantage: it has an impact on performance. Roommate reflection is basically an interpretation operation. We can tell the JVM what we want to do and it meets our requirements. Such operations are always slower than performing the same operations directly

Reflection related main API

  • java.lang.Class : represents a class

  • java.lang.reflect.Method: method representing class

  • java.lang.reflect.Field: member variable representing class

  • java.lang.reflect.Constructor: the constructor representing the class

  • ...

  • package Reflection;
    public class Test01 {
        public static void main(String[] args) throws ClassNotFoundException {
            //Get the Class object of the Class through reflection
            Class c1 = Class.forName("Reflection.User");
            Class c2 = Class.forName("Reflection.User");
            Class c3 = Class.forName("Reflection.User");
            Class c4 = Class.forName("Reflection.User");
            System.out.println(c1.hashCode());
            System.out.println(c2.hashCode());
            System.out.println(c3.hashCode());
            System.out.println(c4.hashCode());
            /*
            21685669
    		21685669
    		21685669
    		21685669
            */
        }
    }
    //Entity class: pojo, entity
    class User{
        private String name;
        private int id;
        private int age;
        public User() {
        }
        public User(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    ", age=" + age +
                    '}';
        }
    }
    
  • It is proved that there is only one class object in the memory of a class. After a class is loaded, the entire structure of the class will be encapsulated in the class object

Class

  • The Public final Class getClass() method is defined in the Object class, which is inherited by all subclasses

  • The return value type of this method is a Class, which is the source of Java reflection. In fact, the so-called reflection is well understood from the running result of the program, that is, the name of the Class can be found through object reflection.

  • Information that an object can get after looking in the mirror:

    • Properties, methods, constructors of a class
    • What interfaces does a class implement
  • For each Class, JRE reserves an object of the same Class type for it. A Class object contains a specific structure

    (class / interface / enum / annotation / primitive type E / void / [])
    • Class itself is a class
    • Class objects can only be created by the system
    • A loaded Class will have a Class instance in the JVM
    • A class object corresponds to a. Class file loaded into the JVM
    • Each Class instance will remember which Class instance generated it
    • Through Class, we can get all the loaded structures in a Class
    • Class class is the root of Reflection. For any class you want to dynamically load and run, only the corresponding class object is fresh
  • Common methods of Class
    • static Class.forName (string name) ------- > returns the class object with the specified class name
    • Object newinstance() --------- call the default constructor to return an instance of Class object
    • Getname() --------- returns the name of the entity (Class, interface, array Class or void) represented by this Class object
    • Class getsuperclass() --------- > returns the parent class object of the current class object
    • Class [] getinterfaces() --------- get the interface of the current class object
    • Classloader getclassloader() --------- returns the class loader of the class place
    • Constructor [] getconstructors() --------- > returns an array containing constructor objects
    • Method getMothod(String name,Class… T) --- > returns a method object whose terrain parameter type bit is paramType
    • Field [] getdeclarefields() ------ > returns an array of field objects

Get an instance of Class

  • If a specific class is known, it can be obtained by the class attribute of the class, which is the most secure and reliable method with high program performance

    Class c1=Person.class;//Here, Person is a collective class by default
    
  • If the instance of a Class is known, call the getClass() method of the instance to get the Class object

    Class c2 =person.getClass();//Here, person defaults to an instance of the class
    
  • The full Class name of a Class is known. Under the Class path, the Class can be obtained through the static method forName() of the Class, which may throw an exception of ClassNotFoundException

    class c3=Class.forName("Class in path")
    
  • The built-in basic data type can directly use the class name. Type

    package Reflection;
    public class Test02 {
        public static void main(String[] args) throws ClassNotFoundException {
            Person person = new Person();
            System.out.println("This man is:"+person.name);
            //Get by instance object
            Class c1= person.getClass();
            System.out.println(c1.hashCode());
            //Obtained by path
            Class c2=Class.forName("Reflection.Student");
            System.out.println(c2.hashCode());
            //Obtained by class name
            Class c3=Student.class;
            System.out.println(c3.hashCode());
            //A wrapper class of a basic built-in Type has a Type attribute
            Class c4=Integer.TYPE;
            System.out.println(c4);
            //Get the Class of the parent Class -- > object Class
            Class c5=c1.getSuperclass();
            System.out.println(c5.hashCode());
        }
    }
    class Person{
        public String name;
        public Person() {
        }
        public Person(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    class Student extends Person{
        public Student(){
            this.name="student";
        }
    }
    class Teacher extends Person{
        public Teacher(){
            this.name="teacher";
        }
    }
    

Can have type of Class object

  • Class: external class, member (diagenetic internal class, static internal class), local internal class, anonymous internal class.

  • Interface interface

  • [] array

  • enum enumeration

  • Annotation: annotation @ interface

  • primitive type: basic data type

  • void

      Class c1=Object.class;//class
            Class c2=Comparable.class;//Interface
            Class c3=String[].class;//One dimensional array
            Class c4=int[][].class;//Two dimensional array
            Class c5=Override.class;//annotation
            Class c6= ElementType.class;//enumeration
            Class c7=Integer.class;//Basic data type
            Class c8=void.class;//void
            Class c9=Class.class;//Class
            /*
            class java.lang.Object
            interface java.lang.Comparable
            class [Ljava.lang.String;
            class [[I
            interface java.lang.Override
            class java.lang.annotation.ElementType
            class java.lang.Integer
            void
            class java.lang.Class
    
             */
    
  • As long as the element has the same type, it is the same Class

    package Reflection;
    public class Test04 {
        public static void main(String[] args) {
            int[] a=new int[100];
            int[] b=new int[10];
            Class c1=a.getClass();
            Class c2=b.getClass();
            System.out.println(c1.hashCode());
            System.out.println(c2.hashCode());
            /*
            21685669
            21685669
             */
        }
    }
    

Java Memory Analysis

  • Heap: store new objects and arrays, which can be shared by all threads and will not be referenced by other objects
  • Stack: store the basic variable type (it will contain the specific value of the basic type), and the variable of the reference object (it will store the specific address of the reference in the heap)
  • Method area: can be shared by all threads, including all class and static variables
  • When a program actively uses a class, if the class has not been loaded into memory, the system initializes the class in three steps
    • Class loading: read the class file of the class into memory and create a java.lang.Class Object. This is done by the classloader
    • Class link: merges the binary data of the class into the JRE
    • Class initialization: the JVM is responsible for class initialization

Class loading and ClassLoader understanding

  • Load: load the bytecode content of the class file into memory, convert the static data into the runtime data structure of the method area, and then generate a java.lang.Class object
  • Link: the process of merging the binary code of a Java class into the running state of a JVM
    • Verification: make sure the loaded class information conforms to the JVM specification, and there is no security problem
    • Preparation: the stage of formally allocating memory for class variables (static) and setting the default initial value of class variables, all of which will be allocated in the method area.
    • Resolution: the process of replacing the symbolic reference (constant name) in the virtual machine constant pool with the direct reference (address).
  • initialization:
    • The process of executing the class constructor () method. The class constructor method is generated by automatically collecting the assignment actions of all class variables in the class at compile time and merging the statements in the static code block. (class constructors construct class information, not class object constructors)
    • When initializing a class, if you find that its parent class has not been initialized, you need to trigger the initialization of its parent class first.
    • Virtual chance ensures that the () method of a class is locked and synchronized correctly in a multithreaded environment.

When will class initialization occur

  • Active reference of class (class initialization must occur)

    • When the virtual machine starts, initialize the class of the main() method first
    • new an object of a class
    • Calling static members (except for final constants) and static methods of a class
    • use java.lang.reflect The method of the package makes a reflection call on the class
    • When a class is initialized and its parent class is not initialized, its parent class will be initialized first
  • Passive reference to class (class initialization does not occur)

    • When accessing a static domain, only the classes that actually declare the domain will be initialized. For example, when a static variable of a parent class is referenced through a subclass, it will not cause the subclass to initialize

    • Defining a class reference through an array does not trigger class initialization

    • Reference constants do not trigger class initialization (constants are stored in the constant pool of the calling class at the link stage)

      package Reflection;
      import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
      import org.w3c.dom.ls.LSOutput;
      public class Test05 {
          public static void main(String[] args) throws ClassNotFoundException {
              //Active call
              Son son=new Son();//Parent class loaded, child class loaded
              Class.forName("Reflection.Son");//The parent class is loaded and the child class is loaded (reflection also produces active references)
              //Methods that do not produce references to classes
              System.out.println(Son.b);//The parent class is loaded; 2. Only the parent class is loaded, but the child class is not loaded
              Son [] array=new Son[5];//No load
              System.out.println(Son.M);//final decoration, no load
          }
      }
      class Father{
          static int b=2;
          static {
              System.out.println("Parent class loaded");
          }
      }
      class Son extends Father{
          static {
              System.out.println("Subclass loaded");
              m=300;
          }
          static int m=100;
          static final int M=1;
      }
      

The function of classloader

  • Load the bytecode content of the class file into memory, convert the static data into the runtime data of the method, and then generate a Java representing the class in the heap, lang.Class Object, as the access entry of method to middle class data

  • Class caching: the standard Java se class loader can find classes as required, but once a class is loaded into the class loader, it will maintain (CACHE) for a period of time. However, the JVM garbage collection mechanism can recycle these class objects

    . java file – > java compiler – >. Class file – > class loader – > bytecode checker – > interpreter – > operating system platform
    Bootstrap loader: responsible for the Java platform core library, which cannot be obtained directly
    Extension class loader: responsible for jar package or - D under jre/lib/ext directory java.ext.dirs Package the jar in the specified directory into the working library
    System classloader: responsible for java -classpath or -D java.class.path The classes and jar s in the directory are the most commonly used loaders
package Reflection;
public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException {
        //Get system classloader
        ClassLoader systemClassLoader=ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2
        //Get the system classloader's parent classloader -- > extension loader
        ClassLoader parent=systemClassLoader.getParent();
        System.out.println(parent);//sun.misc.Launcher$ExtClassLoader@14ae5a5
        //Get the parent loader of extension class loader -- > root loader (C/C + +)
        ClassLoader parent1=parent.getParent();
        System.out.println(parent1);//null
        //The loader loaded when testing the current class
        ClassLoader classLoader=Class.forName("Reflection.Test06").getClassLoader();
        System.out.println(classLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2
        //Who loads when testing JDK's built-in classes
        classLoader=Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classLoader);//null
        //How to get the path that system classloader can load
        System.out.println(System.getProperty("java.class.path"));
        /*
        D:\java\JDK\jre\lib\charsets.jar;
        D:\java\JDK\jre\lib\deploy.jar;
        D:\java\JDK\jre\lib\ext\access-bridge-64.jar;
        D:\java\JDK\jre\lib\ext\cldrdata.jar;
        D:\java\JDK\jre\lib\ext\dnsns.jar;
        D:\java\JDK\jre\lib\ext\jaccess.jar;
        D:\java\JDK\jre\lib\ext\jfxrt.jar;
        D:\java\JDK\jre\lib\ext\localedata.jar;
        D:\java\JDK\jre\lib\ext\nashorn.jar;
        D:\java\JDK\jre\lib\ext\sunec.jar;
        ...
        */
    }
}

Get the complete structure of the runtime class

Through reflection, you can get the complete structure of the runtime class, including
  • Field: field of all classes (property)

  • Method: all methods

  • Constructor: all constructors

  • Supreme: inherited parent class

  • Interface: implement all interfaces

  • Annotation: Annotation

    package Reflection;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    public class Test07 {
        public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
            Class c1=Class.forName("Reflection.User");
            //Get the name of the class
            System.out.println(c1.getName());//Reflection.User  Package name + class name
            System.out.println(c1.getSimpleName());//User package name
            //Get the properties of the class
            Field[] fields=c1.getDeclaredFields();
            for (Field field : fields) {
                System.out.println(field);
                //private java.lang.String Reflection.User.name
                //private int Reflection.User.id
                //private int Reflection.User.age
            }
            //Gets the value of the specified property
            Field name=c1.getDeclaredField("name");
            System.out.println(name);//private java.lang.String Reflection.User.name
            //How to get a class
            System.out.println("==============================================");
            Method[] methods=c1.getMethods();//Get all public methods of this class and its parent class
            for (Method method : methods) {
                System.out.println("natural"+method);
            }
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            methods=c1.getDeclaredMethods();//Get all methods of this class
            for (Method method : methods) {
                System.out.println(method);
            }
            System.out.println("**************************************");
            //Get the specified method
            //It's only possible to overload, so sometimes you need input types of well-known methods
            Method getName=c1.getMethod("getName",null);
            Method setName=c1.getMethod("setName", String.class);
            System.out.println(getName.getName());//getName
            System.out.println(setName);//public void Reflection.User.setName(java.lang.String)
            System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
            //Get the specified constructor
            Constructor[] constructors=c1.getConstructors();
            for (Constructor constructor : constructors) {
                System.out.println(constructor);
                //public Reflection.User()
                //public Reflection.User(java.lang.String,int,int)
            }
            constructors=c1.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                System.out.println(constructor);
                //public Reflection.User()
                //public Reflection.User(java.lang.String,int,int)
            }
            //Get the specified constructor
            Constructor constructor=c1.getDeclaredConstructor(String.class,int.class,int.class);//Specifies the type of parameter the constructor constructs
            System.out.println("appoint"+constructor);
        }
    }
    

Summary:

  • In practice, the operation code that obtains the information of the class is not often developed

  • Be familiar with java.lang.reflect Function of package, reflection mechanism

  • How to get the names, modifiers, etc. of attributes, methods, constructors

    What can I do with a Class object?

    • Create an object with a parameter constructor

      • Get the constructor of the specified formal parameter of this Class through getDeclaredConstructor() of Class
      • An object array is passed in the parameter of the constructor, which contains all the parameters needed in the constructor
      • Instantiate objects with Constructor
    • Create object of Class: call newInstance() method of Class object

      • Class must have a parameterless constructor
      • Class's constructor needs sufficient access rights
    • Call the specified method

      • getMethod(…) Method takes a method and sets the parameter type of the method
      • *. invoke (object, "value of method")
      • If the original method has no return value, null will be returned
      • If the original method is static, the object can be null
      • If the original method parameter list is empty, the value of the method can be null
      • If the original method is declared as private, then the setAccessible(true) method is called to access the private method before invoke.
    • setAccessible

      • Method and Field, Constructor objects have setAccessible() methods.
      • setAccessible is used to start and Jin Yong access security checks
      • If the parameter value is true, the Java language access check will be cancelled when using the object reflected by knowledge
        • Improve the efficiency of reflection. If reflection must be used in the code and the code needs to be called frequently, please set it to true
        • Yes, private members who could not have access can also have access
package Reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//Dynamic creation of objects, through reflection, keyword newInstance()
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1=Class.forName("Reflection.User");
        //Construct an object
        User user=(User)c1.newInstance();//Essentially calling the nonparametric construction of a class
        System.out.println(user);//User{name='null', id=0, age=0}
        //To create an object through a constructor and call a parameter constructor
        Constructor constructor=c1.getDeclaredConstructor(String.class,int.class,int.class);
        User user2=(User)constructor.newInstance("Tom",001,18);
        System.out.println(user2);//User{name='Tom', id=1, age=18}
        //Calling normal methods through reflection
        User user3=(User)c1.newInstance();
        //Get a method by reflection
        Method setName=c1.getDeclaredMethod("setName", String.class);
        //invoke: meaning of activation
        //(object, "value of method")
        setName.invoke(user3,"Tom");
        System.out.println(user3.getName());//Tom
        //Manipulate attributes by reflection
        User user4=(User)c1.newInstance();
        Field name=c1.getDeclaredField("name");
        name.setAccessible(true);
        name.set(user4,"tom2");
        System.out.println(user4.getName());//We can't directly operate the private property. We need to close the program's security add-on test tom2
        Field name1=c1.getDeclaredField("name");
        User user5=(User)c1.newInstance();
        name1.setAccessible(true);
        name.set(user5,"lucy");
        System.out.println(user5.getName());//lucy proves that there is no difference between get... And newInstance
    }
}

Reflection operation generics

  • Java uses the mechanism of generic erasure to introduce generics. Generics in Java are only used by the compiler javac to ensure the security of data and avoid the problem of forced type conversion. However, once the compilation is completed, all types related to generics are erased

  • In order to operate on these types through reflection, Java has added ParemeterizedType,GenericArrayType

  • TypeVariable and WildcardType set types to represent types that cannot be spoofed into class classes, but what are the original types named

  • ParemeterizedType: indicates a parameterized type, such as Collection

  • GenericArrayType: an array type indicating that an element type is a parameterized type or a type variable

  • TypeVariable: a common interface for various types of variables

  • WildcardType: represents a wildcard type expression

    package Reflection;
    import java.lang.reflect.Method;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.List;
    import java.util.Map;
    public class Test09 {
        public Map<String,User> Test01(){
            System.out.println("Test01");
            return null;
        }
        public static void main(String[] args) throws NoSuchMethodException {
            Method method=Test09.class.getMethod("test01",Map.class, List.class);
            Type[] genericparameterTypes=method.getGenericParameterTypes();
            for (Type genericparameterType : genericparameterTypes) {
                System.out.println(genericparameterType);
                if (genericparameterType instanceof ParameterizedType){
                    Type[] actualTypeArguments=((ParameterizedType)genericparameterType).getActualTypeArguments();
                    for (Type actualTypeArgument : actualTypeArguments) {
                        System.out.println(actualTypeArgument);
                    }
                }
            }
        }
    }
    

Comment on reflection operation

  • getAnnotations
  • getAnnotation

Practice ORM

  • ORM----Object relationship Mapping – > object relationship mapping
  • Class corresponds to table structure
  • Property and field correspondence
  • Object and record correspond
  • Require annotation and reflection to complete the mapping between class and table structure
package Reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test10 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1=Class.forName("Reflection.Student2");
        //Get comments by reflection
        Annotation[] annotations=c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //Get the value of the annotation's value
        TebleM tebleM=(TebleM)c1.getAnnotation(TebleM.class);
        String value=tebleM.value();
        System.out.println(value);
        //Get annotation specified by class
        Field f=c1.getDeclaredField("name");
        FieilM annotion=f.getAnnotation(FieilM.class);
        System.out.println(f);
        System.out.println(annotion.columnName());
        System.out.println(annotion.type());
        System.out.println(annotion.lenth());
    }
}
@TebleM("db_student")
class Student2{
    @FieilM(columnName = "db_id",type = "int",lenth = 10)
    private int id;
    @FieilM(columnName = "db_age",type = "int",lenth = 10)
    private  int age;
    @FieilM(columnName = "db_name",type = "char",lenth = 3)
    private  String name;

    public Student2() {
    }

    public Student2(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TebleM{
    String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieilM{
    String columnName();
    String type();
    int lenth();
}

Posted by marowa on Wed, 10 Jun 2020 22:43:44 -0700