Crazy God. Java annotation and reflection learning notes.

1, Annotation

1. Introduction to annotation

What is annotation

  • Annotation is from jdk5 0 began to introduce new technologies

  • Function of Annotation:

    • It is not the procedure itself, and the procedure can be explained (this is no different from comments).
    • It can be read by other programs (such as compiler, etc.)
  • Format of Annotation:

    • Annotations exist in the code as "@ annotation name". You can also add some parameter values, for example. For example: @ SuppressWarnings(value = "unchecked")
  • Where is Annotation used?

    • It 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.

2. Built in annotation

  • @Override: defined in Java In lang. override, this annotation is only applicable to rhetoric, indicating that one method declaration intends to override another method declaration in the superclass
  • @Deprecated: defined in Java In lang. deprecated, this annotation can be used for rhetoric, attributes, and classes to indicate that programmers are not encouraged to use such elements, usually because it is dangerous or there are better choices
  • @SuppressWarnings: defined in Java Lang. SuppressWarnings, used to suppress compile time warnings
    • Different from the previous two comments, you need to add a parameter to use it correctly. These parameters have been defined. We can use them selectively
    • @SuppressWarings("all")
    • @SuppresSWarnings("unchecked")
    • @SuppressWarnings(value={"unchecked" ,"deprecation"})
      Wait
package com.annotation;

import java.util.ArrayList;
import java.util.List;

//What is annotation
public class Test01 extends Object{

    //@Override overridden annotation
    @Override
    public String toString() {
        return super.toString();
    }

    //Deprecated is not recommended for programmers, but it can be used, or there are better methods.
    @Deprecated
    public static void test(){
        System.out.println("Deprecated");
    }

    @SuppressWarnings("all")
    public void test01(){
        List list = new ArrayList<>();
    }

    public static void main(String[] args) {
        test();
    }
}

3. Meta annotation

  • The function of meta annotation is to annotate other annotations. Java defines four standard meta annotation types, which are used to describe other annotation types

  • These types and the classes they support are in Java You can find it in the lang.annotation package (@Target , @Retention, @Documented , @Inherited).

    • @Target: used to describe the scope of use of annotations (i.e. where the described annotations can be used).

    • @Retention: indicates the level at which the annotation information needs to be saved. It is used to describe the annotation life cycle.

      • (SOURCE < CLASS < RUNTIME)
    • @Document: note that the annotation will be included in javadoc

    • @Inherited: indicates that the subclass can inherit the annotation in the parent class

package com.annotation;

import java.lang.annotation.*;

//Test meta annotation
@MyAnnotation
public class Test02 {
    @MyAnnotation
    public void test(){

    }
}


//Target indicates where our annotations can be used.
@Target(value = {ElementType.METHOD,ElementType.TYPE})

//Retention indicates where our annotation is still valid.
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME)

//Documented indicates whether our annotations are generated in JAVAdoc.
@Documented

//The Inherited subclass can inherit the annotation of the parent class.
@Inherited

//Define an annotation
@interface MyAnnotation{

}

4. User defined annotation

  • When you use * * @ interface * * to customize annotations, java.java.java is automatically inherited lang.annotation. Annotation interface
  • analysis:
    • @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
    • The return value type is the type of the parameter (the return value can only be the 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 elements must have values. When defining annotation elements, we often use an empty string with 0 as the default value
package com.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//Custom annotation
public class Test03 {
    //Annotations can display assignments. If there is no default value, we must assign a value to the annotation.
    @MyAnnotation2(age = 18,name = "Qin Jiang")
    public void test(){}

    @MyAnnotation3("Qin Jiang")//If there is only one value in the defined annotation and it is value, you can omit to write value.
    public void test2(){}
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //Annotated parameters: parameter type + parameter name ();
    String name() default "";
    int age();
    int id() default -1;//If the default value is - 1, it means that it does not exist.
    String[] schools() default{"Tsinghua University","Peking University"};
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();
}

2, Reflection mechanism

1. Overview of java reflection mechanism

Static VS dynamic language

Dynamic language

  • It is a kind of language that can change its structure at run time: for example, new functions, objects and even code can be introduced, existing functions can be deleted or other structural changes. Generally speaking, the code can change its structure according to some conditions at run time.
  • Main dynamic languages: Object-C, c#, JavaScript, PHP, Python, etc.

Static language

  • Corresponding to dynamic language, the language with immutable runtime structure is static language. Such as Java, C, C + +.
  • Java is not a dynamic language, but Java can be called a "quasi dynamic language". That is, Java has certain dynamics. We can use reflection mechanism to obtain characteristics similar to dynamic language. The dynamic nature of Java makes programming more flexible!

Java Reflection

  • Reflection is the key to Java being regarded as a dynamic language. Reflection mechanism allows programs 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.
Class C = Class forName("java.lang.String")
  • After loading the Class, a Class object 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. Therefore, we vividly call it reflection

Research and application of Java reflection mechanism

Functions provided by Java reflection mechanism

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

Advantages and disadvantages of Java reflection

advantage:

  • It can dynamically create objects and compile, reflecting great flexibility

Disadvantages:

  • It has an impact on performance. Using 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 operation directly.

Main API s related to reflection

  • java.lang.Class: represents a class
  • java.lang.reflect.Method: represents the method of the class
  • java.reflect.Field: represents the member variable of the class
  • java.lang.reflect.Constructor: represents the constructor of the class
  • ...
package com.reflection;

//What is reflection
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {
        //Get the class object of the class through reflection
        Class c1 = Class.forName("com.reflection.User");
        System.out.println(c1);

        Class c2 = Class.forName("com.reflection.User");
        Class c3 = Class.forName("com.reflection.User");
        Class c4 = Class.forName("com.reflection.User");

        //A Class has only one Class and object in memory.
        //After a Class is loaded, the whole structure of the Class will be encapsulated in the Class object.
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
        System.out.println(c4.hashCode());
    }
}


//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 +
                '}';
    }
}

2. Understand Class and get Class instances

Class class

  • The following methods are defined in the Object class, which will be inherited by all subclasses
public final Class getClass()
  • The type of the return value of the above method is a Class class, which is the source of Java reflection. In fact, the so-called reflection is also well understood from the running results of the program, that is, the name of the Class can be obtained through object reflection.

  • The information that can be obtained after the object looks in the mirror: the properties, methods and constructors of a Class, and which interfaces a Class implements. For each Class, the JRE keeps an object of the same Class type for it. A Class object contains information about a specific structure (class/interface/enum/annotation/primitive type/void / []).
    • Class itself is also a class
    • Class objects can only be created by the system
    • A loaded Class has only one Class instance in the JVM
    • A class object corresponds to a class loaded into the JVM Class file
    • Each Class instance will remember which Class instance it was generated from
    • All loaded structures in a Class can be completely obtained through Class
    • Class is the root of Reflection. For any class you want to dynamically load and run, you have to obtain the corresponding class object first

Common methods of Class

Get an instance of Class

  • If a specific class is known, it is obtained through the class attribute of the class. This method is the most safe and reliable, and the program performance is the highest.
Class clazz = Person.class;
  • Given an instance of a Class, call the getClass() method of the instance to get the Class object
Class clazz = person.getClass();
  • If the full Class name of a Class is known, and the Class is in the Class path, you can get it through the static method forName() of Class class. ClassNotFoundException may be thrown
Class clazz = Class.forName("demo01.Student");
  • The built - in basic data type can use the class name directly Type.

  • You can also use ClassLoader, which we will explain later

package com.reflection;

import java.lang.annotation.Inherited;

//What is the relationship between the creation method of test Class and
public class Test03 {
    public static void main(String[] args) throws ClassNotFoundException {
        Person person = new Student();
        System.out.println("This person is:"+person.name);

        //Method 1: obtained by object
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        //Method 2: forname
        Class c2 = Class.forName("com.reflection.Student");
        System.out.println(c2.hashCode());

        //Method 3: pass the class name. Class get
        Class c3 = Student.class;
        System.out.println(c3.hashCode());

        //Method 4: packaging classes of basic built-in types have a Tpye attribute.
        Class c4 = Integer.TYPE;
        System.out.println(c4);

        //Get parent type
        Class c5 = c1.getSuperclass();
        System.out.println(c5);

    }
}


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";
    }
}

What types can have Class objects?

  • Class: external class, member (member 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
package com.reflection;

import java.lang.annotation.ElementType;

//All types of class es
public class Test04 {
    public static void main(String[] args) {
        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

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
        System.out.println(c7);
        System.out.println(c8);
        System.out.println(c9);
    }
}


3. Class loading and ClassLarder

Java Memory Analysis

Understanding: class loading process

  • When a program actively uses a class, if the class has not been loaded into memory, the system will initialize the class through the following three steps.

Class loading and ClassLoader understanding

  • Load: load the bytecode content of the class file into memory, convert these static data into the runtime data structure of the method area, and then generate a Java. Net file representing this class Lang.class object

  • Link: the process of merging the binary code of Java classes into the running state of the JVM.

    • Verification: ensure that the loaded class information complies with the JVM specification and there are no security problems
    • Preparation: the stage of formally allocating memory for class variables (static) and setting the default initial value of class variables. These memory will be allocated in the method area.
    • Resolution: the process of replacing the symbolic reference (constant name) in the virtual machine constant pool with a direct reference (address).
  • initialization:

    • The process of executing the < clinit > () method of the class constructor. The class constructor < clinit > () method is generated by the combination of the assignment action of all class variables in the class automatically collected at compile time and the statements in the static code block. (the class constructor is used to construct class information, not the constructor to construct the class object.).
    • When initializing a class, if it is found that its parent class has not been initialized, the initialization of its parent class needs to be triggered first.
    • Virtual opportunity ensures that the < clinit > () method of a class is locked and synchronized correctly in a multithreaded environment.
package com.reflection;

/*
1.When loaded into memory, a Class object corresponding to the Class will be generated.
2.Link, m=0 after the end of the link
3.initialization
     <clinit>(){
        System.out.println("A Class static code block initialization "");
        m=300;
        m=100;
     }

     m=100;
 */
public class Test05 {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(A.m);
    }
}


class A{
    static {
        System.out.println("A Class static code block initialization");
        m = 300;
    }

    static int m = 100;

    public A(){
        System.out.println("A Class");
    }
}

When does class initialization occur?

  • Active reference of class (class initialization must occur):

    • When the virtual machine starts, first initialize the class where the main method is located.
    • new is an object of a class.
    • Call static members (except final constants) and static methods of the class.
    • Using Java The method of lang.reflect package makes reflection calls to the class.
    • When initializing a class, if its parent class is not initialized, its parent class will be initialized first.
  • Passive reference of class (class initialization will not occur):

    • When accessing a static domain, only the class that actually declares the domain will be initialized. For example, when a static variable of a parent class is referenced through a subclass, the subclass will not be initialized.
    • Defining a class reference through an array does not trigger the initialization of this class.
    • Reference constants do not trigger the initialization of this class (constants are stored in the constant pool of the calling class in the link phase).
package com.reflection;

//When will the test class initialize
public class Test06 {

    static {
        System.out.println("Main Class loaded!");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Active reference
        //Son son = new Son();

        //Reflection also produces active references
        //Class.forName("com.reflection.Son");

        //A method that does not generate a reference to a class
        //System.out.println(Son.b);

        //Son[] array = new Son[5];

        System.out.println(Son.M);
    }
}

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;
}

Role of class loader

  • The function of class loading: load the bytecode content of the class file into memory, convert these static data into the runtime data structure of the method area, and then generate a Java. Net file representing this class in the heap Lang. class object, as the access entry of class data in the method area.
  • 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 be loaded
    Keep loading (caching) for a period of time. However, the JVM garbage collection mechanism can recycle these Class objects.

  • Class loader is used to load classes into memory. The JVM specification defines loaders for classes of the following types.

package com.reflection;

public class Test07 {
    public static void main(String[] args) throws ClassNotFoundException {

        //Gets the loader of the system class.
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);

        //Gets the parent class loader -- > extension class loader of the system class loader.
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println(parent);

        //Get the parent class loader -- > root loader of the extension class loader (C/C + +)
        ClassLoader parent1 = parent.getParent();
        System.out.println(parent1);

        //Test which loader loads the current class.
        ClassLoader classloader = Class.forName("com.reflection.Test07").getClassLoader();
        System.out.println(classloader);

        //Test who loaded the JDK built-in classes.
        classloader = Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classloader);


        //How to get the path that the system class loader can load.
        System.out.println(System.getProperty("java.class.path"));

        /*
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\charsets.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\deploy.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\javaws.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\jce.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfr.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\jsse.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\management-agent.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\plugin.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\resources.jar;
        C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar;
        E:\java-idea-workplace\Javase02\out\production\Annotation and reflection;
        E:\idea2020\IntelliJ IDEA 2018.3.3\lib\idea_rt.jar
         */


        //Parent delegation mechanism: if you create a new package, you will find it on the Internet layer by layer according to the user loader, extension loader and root loader. If the package name is duplicate, the new package will not be available.
        //Multiple tests will be carried out to ensure safety.
        //For example, a new Java Lang. string, the newly created package is unavailable.

    }
}

4. Get the complete structure of the runtime class

  • Get the complete structure of the runtime class through reflection:

    Field,Method,Constructor,Superclass,Interface,Annotation.

    • All interfaces implemented
    • Inherited parent class
    • All constructors
    • All methods
    • All fields
    • annotation
    • . . .
package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//Gets information about the class.
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.reflection.User");

        //Gets the name of the class
        System.out.println(c1.getName());//Get package name + class name
        System.out.println(c1.getSimpleName());//Get class name

        //Get the properties of the class
        System.out.println("====================================");
        Field[] fields = c1.getFields();//Only public properties can be found

        fields = c1.getDeclaredFields();//Find all properties
        for (Field field : fields) {
            System.out.println(field);
        }

        //Gets the value of the specified property
        Field name = c1.getDeclaredField("name");
        System.out.println(name);

        //Method to get 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);
        }
        methods = c1.getDeclaredMethods();//Get all the methods of this class.
        for (Method method : methods) {
            System.out.println("getDeclaredMethods: "+method);
        }

        //Gets the specified method
        //heavy load
        System.out.println("====================================");
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);

        //Gets the specified constructor
        System.out.println("====================================");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("Good distinction:"+constructor);
        }

        //Gets the specified constructor
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println("appoint:"+declaredConstructor);
    }
}

Summary

  • In the actual operation, the operation code to obtain the class information is not often developed.
  • Be familiar with Java Function of lang.reflect package and reflection mechanism.
  • How to get the names and modifiers of properties, methods and constructors.

5. Create the object of the runtime class

What can I do with a Class object?

  • Create Class object: call newInstance() method of Class object.
    1. Class must have a parameterless constructor.
    2. The constructor of the class needs sufficient access rights.

**Thinking** Can't you create an object without a parameterless constructor? As long as the constructor in the class is explicitly called during the operation and the parameters are passed in, the operation can be instantiated.

  • The steps are as follows:
    1. Get the constructor of the specified parameter type of this Class through getdeclaraedconstructor (Class... parameterTypes) of Class class.
    2. Pass an object array into the formal parameters of the constructor, which contains all the parameters required by the constructor.
    3. Instantiate the object through the Constructor.
package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//Dynamically create objects through reflection.
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //Get Class object
        Class c1 = Class.forName("com.reflection.User");

        //Construct an object.
        //Not without a parameterless constructor.
        User user = (User)c1.newInstance();//The essence is to call the parameterless construction of the class.
        System.out.println(user);

        //Create objects through constructors.
        //This is possible without a parameterless constructor.
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 =(User)constructor.newInstance("Qin Jiang",001,18);
        System.out.println(user2);

        //Call normal methods through reflection.
        User user3 = (User) c1.newInstance();
        //Get a method by reflection
        Method setName = c1.getDeclaredMethod("setName", String.class);

        //invoke: activate.
        //(object, "value of method")
        setName.invoke(user3,"Mad God");
        System.out.println(user3.getName());

        //Operation properties by reflection
        System.out.println("==============================================");
        User user4 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");

        //Private properties cannot be operated directly. We need to turn off the security detection of the program and setAccessible (true) of the property or method.
        name.setAccessible(true);
        name.set(user4,"Mad god 2");
        System.out.println(user4.getName());
    }
}

6. Call the specified structure of the runtime class

Call the specified method

  • Through reflection, the Method in the class is called and completed through the Method class.
    1. Get a Method object through the getMethod(String name,Clas..parameterTypes) Method of Class class, and set the parameter type required for this Method operation.
    2. Then use Object invoke(Object obj, Object[] args) to call and pass the parameter information of the obj object to be set to the method.

  • Object invoke(Object obj, Object ... args)
    • Object corresponds to the return value of the original method. If the original method has no return value, null is returned
    • If the original method is a static method, the formal parameter object can be null
    • If the original method parameter list is empty, Object[] args is null
    • If the original method is declared as private, you need to explicitly call the setAccessible(true) method of the method object before calling the invoke() method to access the private method.

setAccessible

  • Method, Field and Constructor objects all have setAccessible() methods.
  • setAccessible is a switch that enables and disables access security checks.
  • If the parameter value is true, it indicates that the Java language access check should be cancelled when the reflected object is used.
    • Improve the efficiency of reflection. If reflection must be used in the code, and the code of this sentence needs to be called frequently, please set it to true.
    • So that private members that cannot be accessed can also be accessed
  • If the parameter value is false, it indicates that the reflected object should implement Java language access check
  • Performance test
package com.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//Analytical performance test
public class Test10 {
    //Normal mode call
    public static void test01() {
        User user = new User();

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("1 billion times in ordinary way:"+(endTime-startTime)+"ms");
    }

    //Reflection mode call
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1 =user.getClass();

        Method getName = c1.getDeclaredMethod("getName", null);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("1 billion times in reflection mode:"+(endTime-startTime)+"ms");
    }

    //Reflection mode call, turn off detection
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1 =user.getClass();

        Method getName = c1.getDeclaredMethod("getName", null);
        getName.setAccessible(true);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Close detection and execute 1 billion times:"+(endTime-startTime)+"ms");
    }


    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        test01();
        test02();
        test03();
    }

}

Reflection operation generics

  • Java uses the generic erasure mechanism to introduce generics. Generics in Java are only used by the compiler javac to ensure data security and avoid forced type conversion. However, once the compilation is completed, all types related to generics are erased.
  • In order to manipulate these types through reflection, Java has added ParameterizedType, GenericArrayType, TypeVariable and WildcardType to represent types that cannot be classified into Class but have the same name as the original type.
  • ParameterizedType: represents a parameterized type, such as Collection.
  • GenericArrayType: indicates that an element type is an array type of parameterized type or type variable.
  • TypeVariable: it is the public parent interface of various types of variables.
  • WildcardType: represents a wildcard type expression.
package com.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

//Get generics through reflection
public class Test11 {

    public void test01(Map<String ,User> map, List<User> list){
        System.out.println("test01");
    }

    public Map<String,User> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Method method = Test11.class.getMethod("test01", Map.class, List.class);

        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("Parameterized type of generic type:"+genericParameterType);
            if (genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println("Parameterization type:"+actualTypeArgument);
                }
            }
        }
        System.out.println("=====================================================");

        method = Test11.class.getMethod("test02",null);
        Type genericReturnType = method.getGenericReturnType();

        if (genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println("Parameterization type:"+actualTypeArgument);
            }
        }
    }
}


Reflection operation annotation

  • getAnnotations()
  • getAnnotation()
package com.reflection;

import javafx.scene.control.Tab;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//To practice reflection
public class Test12 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("com.reflection.Student2");

        //Get annotations through reflection
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //Gets the value of the annotated value
        Tablekuang tablekuang = (Tablekuang)c1.getAnnotation(Tablekuang.class);
        String value = tablekuang.value();
        System.out.println(value);

        //Gets the specified annotation of the class
        Field f = c1.getDeclaredField("name");
        Fieldkuang annotation = f.getAnnotation(Fieldkuang.class);
        System.out.println(annotation.columName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }
}

@Tablekuang("db_student")
class Student2{

    @Fieldkuang(columName = "db_id",type = "int",length = 10)
    private int id;
    @Fieldkuang(columName = "db_age",type = "int",length = 10)
    private int age;
    @Fieldkuang(columName = "db_name",type = "varchar",length = 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 + '\'' +
                '}';
    }
}

//Annotation of class name
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablekuang{
    String value();
}

//Attribute annotation
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldkuang{
    String columName();
    String type();
    int length();
}

Exercise: ORM

  • What is ORM?

    • Object relationship Mapping – > Object relationship Mapping.

  • Correspondence between class and table structure

  • Attribute and field correspondence

  • Object and record correspondence

  • Requirement: use annotation and reflection to complete the mapping relationship between class and table structure.

Keywords: Java Back-end

Added by avianrand on Tue, 14 Dec 2021 06:43:34 +0200