This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

What time note

What a comment does: it is not the program itself, it can explain the program (this is no different than a comment)

Can be read by other programs, such as compilers, etc

Annotation format: Annotations exist in code with @annotation names, and you can add parameter values such as: @suppresswarnings (value=”unchecked”) Where is used? Can be attached in the package, class, method, field, such as equivalent to give them added additional auxiliary information, can reflect these metadata access by programming.

Built-in annotations

Override: Defined in java.lang.Override, this annotation applies only to rhetorical methods. Indicates that a method declaration intends to override another method declaration in a superclass. @Deprecated: Used for a rhetorical method, property, or class to indicate that its use is Deprecated, usually because it is dangerous or a better alternative is available. @Suppresswarnings: To suppress compile-time warnings is different from the previous two comments, you need to add a parameter to use it properly. These parameters are already defined, so we can use them selectively.

Custom annotations

When using @Interface custom annotations, the java.lang.annotation.Annotation interface is automatically inherited

Analysis of the

@interface declares an annotation, Each method actually declares a configuration parameter. The name of the method is the name of the parameter. The type of the method is the type of the parameter Annotation elements must have a Value. When we define annotation elements, we often use an empty string with 0 as the default Value

reflection

Dynamic languages are languages that can change their structure at runtime: for example, new functions, objects, and even code can be introduced, existing functions can be removed, or other structural changes can be made. In general terms, code can change its structure according to certain conditions while running. Static languages such as Object-C,C#,JavaScript,Php, And Python are static languages that have immutable runtime structures, such as Java C,C++. Java is not a dynamic language, but Java can be called a “quasi-dynamic language”. Java has a certain dynamic, we can use the reflection mechanism to obtain similar dynamic language characteristics, Java dynamic makes programming time more flexible! Reflection, the key to Java’s recognition as a dynamic language, allows a program to directly manipulate the internal properties and methods of any object at execution time by obtaining the internal information of any class. After the Class is loaded, a class-like object (a Class has only one Classd object) is generated in the method area of the heap memory. This object contains the complete Class structure information. We can see the structure of the class through this object, and this object is like a mirror through which we can see the structure of the class, so we call it a reflection

Java Reflection benefits

Pros: You can create objects and compile them dynamically, giving you a lot of flexibility. Cons: Performance impact. Using reflection is basically an interpreted operation, we can tell the Jvm what we want to do and it meets our requirements

Reflection related apis

Java.lang.reflect.Method: Java.lang.Reflect.Field: java.lang.Reflect. On behalf of the members of the class variables in Java. Lamg. Reflect the Constructor: on behalf of the Constructor of a class

Class Class

The type returned by the above method is a Class Class. This Class is the source of Java reflection. In fact, reflection is easy to understand in terms of the results allowed by the program, so you can use object reflection to find the name of the Class.

The information the object gets when it looks in the mirror: The properties, methods, and constructors of a Class, and the interfaces that a Class implements. For each Class, the Jre reserves an object of type Class. An object Class object contains a particular structure and a Class itself is also a Class object. A Class object can only be created by the system. A loaded Class has only one instance in the Jvm Class class is the root of Reflection. For any class that you want to dynamically load and run, you have to get the corresponding class object first.

Class Class

Static Classforname(String name) returns a Class Object with the specified Class name. Getname () returns an instance of the Class object. Getname () returns an instance of the Class object. Class getSuperClass() returns a Class object of the parent Class of the current Class object. Class [] getInterfaces () gets the ClassLoader of the current Class object Constructor[] getConstructors() returns an array of Constructor objects (Method getMonthod(String)) name,Class… T) returns a Method object whose parameter type is ParamType Field[] getDecaredFields() returns an array of Field objects

How to get an instance of a Class

package com.company;

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

        person student = new student();
        System.out.println(student.name);
        / / the first
        Class<? extends person> aClass2 = student.getClass();
        System.out.println("aClass2 = " + aClass2.hashCode());
// System.out.println("student.hashCode() = " + student.hashCode());
        / / the secondClass<? > aClass = Class.forName("com.company.student");
        System.out.println("aClass.hashCode() = " + aClass.hashCode());
        / / the third kind
        Class<com.company.student> aClass1 = student.class;
        System.out.println("aClass1.hashCode() = " + aClass1.hashCode());
        // Get the parent type
        Class<?> superclass = aClass2.getSuperclass();
        System.out.println(superclass);

    }
}
class person{
   public String name;
         public person(a) {}public person(String name) {
        this.name = name;
    }

    @Override
    public String toString(a) {
        return "person{" +
                "name='" + name + '\' ' +
                '} '; }}class student extends person{


    public student(a) {
        this.name="Students"; }}Copy the code

Those classes have class

package com.company;

import java.lang.annotation.ElementType;

public class Demo1 {
    public static void main(String[] args) {
        Class c1 = Object.class;
        Class c2 = Comparable.class;
        Class c3 = String[].class;
        Class c4 = int[][].class;
        Class c5 = Override.class;
        Class c6 = ElementType.class;
        Class c7 = Integer.class;
        Class c8 = void.class; Class c9 = 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); }}Copy the code

Java memory

Class loading process

When a program actively uses a class, the system passes if the class has not already been loaded into memoryUnderstanding of class loading and ClassLoader

Load: Loads the bytecode contents of the class file into memory, converts the static data into the runtime data structure of the method area, and generates a Java.lang. class object representing the class. To ensure that class information is loaded according to THE JVM specification, no security issues are prepared: To formally allocate memory for class variables and to set the default initialization phase for class variables, this memory will be allocated in the method area. The process of initializing the execution of the class constructor () method by replacing a symbolic reference (constant name) with a direct reference (address) in the virtual machine constant pool. The class constructor < clinit> () method is generated by an assignment action that automatically collects all class variables in the class at compile time and combines statements in a static code block. A class constructor is a constructor that constructs class information, not objects of the class. When initializing a class, if the parent class has not been initialized, the parent class must be initialized first. The virtual machine ensures that the < clinit> () method of a class is properly locked and synchronized in a multithreaded environment.

When does class initialization occur

Active reference to class (class initialization must occur)

When the virtual machine starts, first initialize the class where the main method is located. New an object of the class calls static members of the class (except for final constants) and static methods using the java.lang.Reflect package’s methods. When initializing a class, if its parent class has not been initialized, When a static field is accessed, only the class that actually declared the field is initialized. For example: When referring to a static variable of a parent class through a subclass, it does not cause the subclass to initialize. Class references are defined through an array. Class initialization is not triggered.

Class loaders are used

Class loaders are used to load classes into memory. The Jvm specification defines class loaders of the following types

Bootstrap class loaders

Written in C++, is the JVM’s own class loader, responsible for the Java platform core library. Used to load the core class library, which is not available directly by the loader

Extend the class loader

Responsible for the jre/lib/ext directory jar package or specified directory jar package into the working library

System class loader

The most common loader is the one that wraps classes and jars in the java-classpath or java.class.path directory

Class loaders are used

The class loader loads the bytecode contents of the class file into memory, converts the static data into a runtime data structure in the method area, and then generates a Java.lang. class object in the heap that represents the class, which serves as the access point to the class data in the method area. The standard javaEE classloader can look for classes on demand, but once a Class is loaded into the classloader, it remains (cached) for a period of time, although the JVM garbage collection mechanism can reclaim these Class objects

package com.company;

public class Text7 {
    public static void main(String[] args) throws ClassNotFoundException {
        // Get the system class loader
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println("systemClassLoader = " + systemClassLoader);
        // Obtain the system classloader from the superclass loader --
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println("parent = " + parent);
        // Get the parent loader
        ClassLoader parent1 = parent.getParent();
        System.out.println("parent1 = " + parent1);
        // Which loader is loaded when the current class is testedClass<? > aClass = Class.forName("com.company.Text7");
        System.out.println("aClass = " + aClass);
        // Test the built-in JDK classesClass<? > aClass1 = Class.forName("java.lang.Object");
        System.out.println("aClass1 = " + aClass1);
        // Obtain the path where the system classes are loaded
        System.out.println(System.getProperty("java.class.path")); }}Copy the code

The results ofThe JVM bring to

Get the complete structure of the runtime class

By reflecting access runtime class must complete structure Field, Method, Constructor, Superclass, Interface, the Annotation all Interface implementation All inherited to the parent class constructor All the way all Field notes

package com.company;

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

public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class<? > c1 = Class.forName("com.company.User");
// Get the name of the class
        System.out.println(c1.getName());
        // Get the class name
        System.out.println(c1.getSimpleName());
        // Get the attributes of the class
        System.out.println("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ `");
        // Only public properties can be found
        Field[] fields = c1.getFields();
        for (Field field : fields) {
            System.out.println("field = " + field);
        }
        // Find all
        Field[] declaredFields = c1.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println("field = " + field);
        }
        // Get the specified
        Field name = c1.getDeclaredField("name");
        System.out.println("name = " + name);
        // Get the class method
        System.out.println("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");
        // Obtain all public values for this class and its parent class
        Method[] methods = c1.getMethods();
        for (Method method : methods) {
            System.out.println("method = " + method);
        }
        // Get all methods of this class
        Method[] methods1 = c1.getDeclaredMethods();
        for (Method method : methods1) {
            System.out.println("method = "+ method); }}}Copy the code

Calls the specified method

Object invoke (Object obj ,Object… If the method is static, then the Object obj parameter can be null. If the method is static, then the Object obj parameter can be null. If the original method is declared private, then we need to explicitly call the setAccessible(true) method of the method object before calling this invoke() method

setAccessible

Method and Field,Constuctor objects both have setAccessible () methods. SetAccessible turns on and off access security checks. A value of true indicates that the reflected object should be used without Java language access checks To improve the efficiency of reflection, if the code must use reflection, and the code needs to be called frequently, set this parameter to true so that otherwise inaccessible private members can be accessed. A value of false indicates that the reflected object should be checked for Java language access.

If you use radiation often

package com.company;

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

public class Demo8 {
    // Common method loading
    public static void demo1(a){
        // Get the time
        long start = System.currentTimeMillis();
        User user = new User();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        // Get the end time
        long end = System.currentTimeMillis();
        System.out.println("The common way" +( end-start)+"ms");
    }
    / / reflection
    public static void demo2(a) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // Get the time
        long start = System.currentTimeMillis();
        User user = new User();
        Class<? extends User> aClass = user.getClass();
        Method getName = aClass.getDeclaredMethod("getName".null);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }
        // Get the end time
        long end = System.currentTimeMillis();
        System.out.println("Reflected." +( end-start)+"ms");
    }
    // Reflect off detection
    public static void demo3(a) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // Get the time
        long start = System.currentTimeMillis();
        User user = new User();
        Class<? extends User> aClass = user.getClass();
        Method getName = aClass.getDeclaredMethod("getName".null);
       getName.setAccessible(true);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }
        // Get the end time
        long end = System.currentTimeMillis();
        System.out.println("Reflex off detection" +( end-start)+"ms");
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { demo1(); demo2(); demo3(); }}Copy the code

The results ofThe common way is the fastest way

Reflection operation generics

Java uses a generics eraser mechanism to introduce generics. Generics in Java are only used by the compiler Javac to ensure data security and avoid casting problems, but once the compilation is complete, all types related to generics are erased in order to operate on them through reflection. Java has added parameterizedType,CenericArrayType TypeVariable, and XildcardType types to represent types that cannot be grouped into a Class Class but have the same name as the original type ParameterizedType: indicates a ParameterizedType, such as Collection CenericArrayType: An array type that indicates that an element is a parameterized type or a TypeVariable. TypeVariable: a public parent interface for variables of various types. WildcardType: represents an expression of a WildcardType