“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

Overview of software development

2.1 Software development life cycle

Life cycle: the process from project approval to software discontinuation

  1. Problem definition and planning: at this stage, the software developer and the demander discuss together to determine the software development goals and feasibility
  2. Requirement analysis: in the case of determining the feasibility of software development, the detailed analysis of the software needs to achieve each function. Requirements analysis stage is a very important stage, this stage is done well, will lay a good foundation for the success of the entire software development project.
  3. Software design: this stage mainly according to the results of demand analysis, the whole software system is divided into large and small multiple modules, design the specific structure of each module. Such as system framework design, database design and so on. Software design is generally divided into overall design and detailed design.
  4. Program coding: This stage is to translate the results of the software design into program code that the computer can run. In the program coding must develop a unified, in line with the standard of writing norms. In order to ensure the readability of the program, easy maintenance, improve the efficiency of the program.
  5. Software testing: after the completion of software design, rigorous testing should be carried out to find the problems existing in the whole design process and correct them. The whole test process is divided into three stages: unit test (white box), integration test (black box, functional test, strength performance test) and system test. There are two main test methods: white box test and black box test. In the process of testing, it is necessary to establish a detailed test plan and test strictly according to the test plan to reduce the randomness of testing.
  6. Operation and maintenance: install and deploy the software system, repair the bugs in the software and upgrade the system. After the software development is completed and put into operation, the software cannot continue to adapt to the requirements of users due to various reasons. To extend the service life of software, software must be maintained. Software maintenance includes two aspects: error correction maintenance and improvement maintenance

2.2 Software design principles

In order to improve the efficiency of software development and reduce the cost of software development, an excellent software system should have the following characteristics:

  1. Reusability: Follow DRY(Don’t Repeat Yourself Principle) to reduce duplicate code in software.
  2. Extensibility: When software needs to be upgraded to add new functions, new modules can be easily created on the existing system architecture without changing the existing software structure, and existing modules will not be affected.
  3. Maintainability: When user requirements change, only a small amount of code in a local module needs to be modified.
  4. High cohesiveness: Cohesiveness emphasizes functional connections within a department module. Each module only performs specific functions, and there is no overlap between different modules. High cohesiveness improves software reusability and maintainability.
  5. Low coupling: Coupling emphasizes the relationship between multiple modules. Modules are independent of each other. Modification of one module does not affect other modules. Low coupling improves software maintainability.

2.3. Coding specifications

Basic naming conventions: use meaningful English words, and use a hump notation for multiple words

The package name

All lowercase, domain name written backwards. Module name Component name, for example, com.util

The interface name

Capital letters, adjectives, adverbs. It’s customary to start with I. In this case, I indicates interface, for example, IUserService and IEmployeeService (it is not mandatory but must be considered in combination with other specifications)

Interface implementation class

It is customary to use the END of the Impl, for example, UserServiceImpl and EmployeeServiceImpl

The name of the class

Capital letter, noun. Follow the hump notation. For example, the User, Employ

The method name

The first letter is lowercase. Strive for semantic clarity and use multiple words. Follow the hump notation. For example: getUserInfoByName ()

The variable name

The first letter is lowercase. Follow the hump notation. For example: the userInfo

Constant names

All caps, strive for semantic clarity, use more than one word. Use underscores. For example: MAX_STOCK_COUNT.

Second, software testing

Software testing is often divided into two categories: black box testing and white box testing.

2.1. Black box test

Black box testing, also known as functional testing, through the test to detect whether every function can be normal use, the program as a can’t open the box, in a completely regardless of the program under the condition of internal structure and internal characteristics, tests on the interface of the program, check program function normal use according to the terms of the requirements specifications.

In simple terms: you don’t need to write code, give the input value, and see if the program can output the desired value.

He found the following errors:

  1. Whether the function is incorrect or missing
  2. Whether the interface has errors
  3. Input and output errors
  4. Database access error
  5. Whether there is a performance problem
  6. Initialization and termination errors, etc

2.2. White box test

Developers do the testing. Also known as structural testing, transparent box testing, logic-driven testing, or code-based testing. It is in accordance with the internal structure test procedures, through the test to detect the product internal action in accordance with the provisions of the design specifications of the normal implementation. Testers must examine the internal structure of the program, starting from examining the logic of the program, to obtain test data.

Simply put: you need to write code. Focus on the specific execution flow of the program.

2.3. JUnit Testing

JUnit is a Regression testing framework written by Erich Gamma and Kent Beck. JUnit tests are programmer tests, or white-box tests, because programmers know How and What the software being tested does.

2.3.1 JUnit dependency installation

Since JUnit 4 regression test framework is provided by three parties, not the JDK built-in, all need to use others to import jar package and install the corresponding plug-in, here uses maven as an example, import maven coordinates:

<! -- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
Copy the code

2.3.2 JUnit common annotations

JUnit comes with some common annotations to solve the problem of code duplication

2.3.2.1, @ Before

Decorated methods are executed automatically before testing methods

2.3.2.2, @ After

The decorated method is executed automatically After the test method is executed, as is the code After @After if there is an exception

Configuration file

Normally, IT is OK to save some configuration information for the program to read data dynamically. However, in order to improve efficiency, two files with special characteristics are used as configuration files in the IT industry

  1. The properties file
  2. The XML file

3.1. Properties file

The file is called property file/resource file/configuration file, with Properties as the file suffix. The access feature is the format of KV key-value pair: key=value, and multiple pairs of data are separated by newlines.

Matters needing attention:

  1. In the configuration file, all data is strings and quotation marks are not required.
  2. Spaces are not required in configuration files

3.1.1. Parse the Properties file

If we want to read the data in properties, we can use IO to read the data line by line and split the string by =. However, it is still more troublesome if there is a comment, at this point we can realize such a complicated step, SUN must have written the tool method for us, which is called Properties.

Properties is the Map implementation class. Common operations that can be inherited from map (get,put….) The methods in map, we don’t usually use. Because the properties file is special, we generally use the new methods of the Properties class.

3.1.2 Common apis

  1. public void load(InputStream inStream);Load the contents of the configuration file through the input stream.
  2. public String getProperty(String key);// Get the value from the attribute name
package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/ * * *@author Xiao_Lin
 * @date2020/12/28 now * /
public class ProTest {

  public static void main(String[] args) throws IOException {
    // Read the data in the configuration file
    Properties properties = new Properties();
    // To get a ClassLoder object, it is independent of Thread
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    // The class loader reads the configuration file and returns an input stream
    InputStream stream = loader.getResourceAsStream("user.properties");
    // Load the configuration file
    properties.load(stream);
    System.out.println(properties.getProperty("user"));
    System.out.println(properties.getProperty("password")); }}Copy the code

3.2. XML files

XML(Extensible Markup Language) is an Extensible Markup Language. XML technology is released by the World Wide Web Consortium (W3C). The current version follows one published in 1998 by the W3C.

XML1.0 specification. It is designed to transfer data, not display data (HTML). Its tags are not predefined and require custom tags. It is a W3C recommendation.

3.2.1. Why learn XML

  1. XML is a common format for data exchange.
  2. Many systems use XML for configuration files.
  3. JavaEE frameworks almost all use XML

3.2.2 syntax of XML

  1. XML documents need to be declared in the first line of the document

Four, reflection

4.1. What is Reflection

The dynamic retrieval of class member information (constructors, methods, fields) through bytecode files during program execution is called reflection. The purpose is to create an object, get a method, and call the constructor automatically through the program.

4.2 bytecode objects

Java code goes through three phases:

We can abstract multiple objects into a class by discovering their commonalities. The class is the template of the object, and the entities are the objects

The bytecode is also a real file, each bytecode is an instance, and for the JVM to store this bytecode, it needs to be abstracted into a template, which then creates objects that hold the information of each bytecode. When a piece of bytecode is used (for example, to create a Person object), the class object holding the Person.class content is pulled from the JVM and then instantiated. 3.

The JDK defines the Class java.lang.Class, which contains a large number of gTE-starting methods that use bytecode objects to retrieve information, so when we get bytecode objects we can directly manipulate the constructors, methods, fields and so on in the current bytecode.

4.3. Obtain the bytecode object

From the API, we know that there is no common constructor for a Class because Class objects are automatically built by the Java Virtual machine when the Class is loaded.

Methods a

The bytecode object ** (common) ** is obtained by the forName() method of the Class Class. It is used in configuration files where the Class name is defined. Read files, load classes, and various popular frameworks.

Class.forName(String className);  // Get the bytecode object by the fully qualified class name, which is the package name + type
Class.forName("java.lang.String");  // If it exists in the JVM, throw an exception if it does not
Copy the code

Party to pick up two

GetClass () is used to obtain bytecode objects.

new User().getClass();  // Through the getClass method of the parent Object class
Copy the code

Methods three

Bytecode objects are obtained from the class field of type (base type), mostly for passing parameters.

int.class;
Copy the code

conclusion

  1. The first of these three approaches is the most commonly used and is used in a variety of frameworks.
  2. The same bytecode file (*.class) is loaded only once during a program run, and the class object is the same regardless of which way it is retrieved.
@Test
public  void testGetClass(a) throws Exception {
    // 1 passes the fully qualified name of the Class class.forname ();
    Class clz1 = Class.forName("cn.linstudy.domain.Person");
    // 2 through the object's getClass() method
    Person p = new Person();
    Class clz2 = p.getClass();
    // 3 Use the class field to get the value
    Class clz3 = Person.class;
    // The bytecode is only loaded once, so it is the same regardless of which way the bytecode is retrieved
    System.out.println(clz1 == clz2);   //true
    System.out.println(clz2 == clz3);   //true
    System.out.println(clz1 == clz3);   //true
        // Int and int are not the same data type
    System.out.println(int.class);
    System.out.println(int[].class);
}
Copy the code

4.4. Get the constructor

The purpose of reflection is nothing more than to use a program to dynamically manipulate a class member, such as a method, and the method must have an object in the first place. Objects are created through constructors, so constructors must be obtained first.

4.4.1. Get all constructors

public Constructor
[] getConstructors(); : gets the constructor for all public modifications.

public Constructor
[] getDeclaredConstructors(); Get all constructors (including non-public)

4.4.2. Get the specified constructor

public Constructor getConstructor(Class... parameterTypes);

public Constructor getDeclaredConstructor(Class… parameterTypes)

ParameterTypes: The type of the parameters (the type of the constructor’s argument list).

conclusion

“S” means get multiple. Declared with Declared rights are ignored, even private ones can be obtained.

4.4.3 Get constructor exercise

@Test
public void testGetConstructor(a) throws NoSuchMethodException {
    // Get the bytecode object
    Class clz = Person.class;
    // 1 get all public constructors
    Constructor[] cons1 = clz.getConstructors();
    for(Constructor con : cons1){
        System.out.println(con);
    }
    System.out.println("-- -- -- -- -- -- -- --");
    // 2 Get all constructors, including private
    Constructor[] cons2 = clz.getDeclaredConstructors();
    for(Constructor con : cons2){
        System.out.println(con);
    }
     // 3 Get the no-parameter constructor
    Constructor con1 = clz.getConstructor();
    System.out.println(con1);
    // 4 Get the parameter constructor
    Constructor con2 = clz.getConstructor(Long.class, String.class);
    System.out.println(con2);
    // get the specified private constructor
    Constructor con3 = clz.getDeclaredConstructor(String.class);
    System.out.println(con3);
}
Copy the code

Common mistakes

Parameter mismatch, error reported. The specified constructor could not be found

4.4.4 Call constructor to create object

public Object newInstance(Object... initargs);// initargs: calls the actual arguments passed by the constructor. The argument list must match (type, number, order).

Copy the code
@Test
public void testCreateObject(a) throws Exception {
    // Get the bytecode object
    Class clz = Class.forName("cn.linstudy.domain.Person");
    // Get the constructor with parameters, parameter type
    Constructor con1 = clz.getConstructor(Long.class, String.class);
    // Call the constructor
    Object obj = con1.newInstance(1L."Little Wolf");
    System.out.println(obj);
    // Get the private constructor with parameters
    Constructor con2 = clz.getDeclaredConstructor(String.class);
    // To call a private constructor, you must first make it accessible
    con2.setAccessible(true);
    Object obj2 = con2.newInstance("Small size");
    System.out.println(obj2);
}
Copy the code

Note: You cannot directly access members that do not have permissions (non-public), if you want to use reflection to manipulate members that are not public. You must set an accessible flag.

We tried to privatize the constructor to create objects and were told we didn’t have enough permissions

The solutions are as follows:

Public void setAccessible(Boolean flag): Pass a true indicating access, indicating no permissions

From the API we can see that Constructor,Field, and Method are subclasses of AccessibleObject because all three members can be modified by accessing the private modifier.

package com.test.reflect;

import java.lang.reflect.Constructor;

/ * * *@author Xiao_Lin
 * @date2020/12/28 did * /
public class TestReflect {

  public static void main(String[] args) throws Exception { Class<? > student = Class.forName("com.test.reflect.Student"); System.out.println(student); Constructor<? > constructor = student.getDeclaredConstructor(String.class); constructor.setAccessible(true);
    Object zs = constructor.newInstance("Zhang"); System.out.println(zs); }}Copy the code

Whenever you see a fully qualified name passed in, you’re basically going to use reflection to get the bytecode object by the fully qualified name. Whenever you see no specified constructor but can create an object, it is basically to create an object through the newInstance of bytecode objects.

4.5. Acquisition method

4.5.1 Get all methods

  1. public Method[] getMethods();: All public methods can be obtained, including inherited ones.
  2. public Method[] getDeclaredMethods();Get all methods in this class, including non-public, excluding inherited methods.

4.5.2. Obtain the specified method

  1. public Method getMethod(String name, Class<? >... parameterTypes);

  2. public Method getDeclaredMethod(String name, Class
    … ParameterTypes) :

    Name: indicates the method name. ParameterTypes: indicates the parameter list type of the current method

    Note that to find a specified method, you must use the method signature to locate it, and the method signature = method name + parameter list. The experience is the same as getting a constructor.

4.5.3 Practice of acquiring methods

@Test
public  void testGetMethod(a) throws Exception {
    /** 1 Get all public methods, including the parent 2 get all methods, including private excluding the parent 3 Get public methods, including the parent 4 get private methods with specified parameters, excluding the parent **/
    // 1 gets the bytecode object
    Class clz = Class.forName("cn.linstudy.domain.Person");
    // 2 Gets the constructor to create the object
    // 3
    //1 gets all public methods, including the parent
    Method[] methods = clz.getMethods();
    for(Method m : methods){
        System.out.println(m);
    }
    System.out.println("-- -- -- -- -- -- -- -- --");
    //2 Get all methods, including private but not including parent
    Method[] methods2 = clz.getDeclaredMethods();
    for(Method m : methods2){
        System.out.println(m);
    }
    System.out.println("-- -- -- -- -- -- -- -- --");
    //3 Gets the public method of the specified argument, including the parent class
    Method sayHelloMethod = clz.getMethod("sayHello", String.class);
    System.out.println(sayHelloMethod);
    //4 Gets the private method of the specified argument, excluding the parent class
    Method doWorkMethod = clz.getDeclaredMethod("doWork", String.class);
    System.out.println(doWorkMethod);
}
Copy the code

4.6. Call the method

public Object invoke(Object obj, Object… args); :

Obj: indicates the object on which the method is called..

Args: The return value of the actual argument to the calling method, indicating whether the calling method has a return value, if so, and null if not.

Traditional invocation methods

Student t = new Student(1."Zhang"); 
t.sleep(5);// Zhang SAN, sleep for 5 hours.
Copy the code

Create object call methods using reflection

Method m = CLZ getMethod (" sleep ",int.class);// Find the sleep method.
m.invoke(obj, 5);// Sleep for 5 hours.
Copy the code
public class Person {
    private Long id;
    private String name;
    public Person(a) {}public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    private Person(String name) {
        this.name = name;
    }
    public void sayHello(a){
        System.out.println("hello");
    }
    public String sayHello(String name){
        System.out.println(name + ": hello");
        return "Hello";
    }
    public static void sayHello(String name,Long id){
        System.out.println("Calling static methods");
    }
    private void doWork(a){
        System.out.println("doWork");
    }
    private void doWork(String name){
        System.out.println(name + ": doWork");
    }
    // Getter method setter method
    public String toString(a) {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                '} '; }}Copy the code
@Test
public  void testGetMethod(a) throws Exception {
    // 1 gets the bytecode object
    Class clz = Class.forName("com.reflect.Person");
    // 2 Gets the constructor to create the object
    Object obj = clz.newInstance(); // Use a common no-argument constructor
    // 3
    //1 gets all public methods, including the parent
    Method[] methods = clz.getMethods();
    for(Method m : methods){
        System.out.println(m);
    }
    System.out.println("-- -- -- -- -- -- -- -- --");
    //2 Get all methods, including private but not including parent
    Method[] methods2 = clz.getDeclaredMethods();
    for(Method m : methods2){
        System.out.println(m);
    }
    System.out.println("-- -- -- -- -- -- -- -- --");
    //3 Gets the public method of the specified argument, including the parent class
    Method sayHelloMethod = clz.getMethod("sayHello", String.class);
    System.out.println(sayHelloMethod);
    // Call the method
    Object val1 = sayHelloMethod.invoke(obj, "Zhang");

    System.out.println("1." + val1);
    //4 Gets the private method of the specified argument, excluding the parent class
    Method doWorkMethod = clz.getDeclaredMethod("doWork", String.class);
    System.out.println(doWorkMethod);
    // Set accessibility
    doWorkMethod.setAccessible(true);
    // Call a private method
    doWorkMethod.invoke(obj,"Bill");
     // Call static methods
	Method staticSayHelloMethod = clz.getDeclaredMethod("sayHello", String.class, 
Long.class);
	// There is no object to call, but arguments must be null, otherwise the following arguments will be used as the object to call the method.
	staticSayHelloMethod.invoke(null."Xiao Ming".1L);
}

Copy the code

Note:

  1. Methods can also be modified by access private modifiers, so if you want to access methods that are not public, you need to set them accessible before accessing themmethod.setAccessible(true);.
  2. An object is not required if a static method is called, so the first argument to the Invoke method is passed directly by the object Can be null.

4.7. Get fields

4.7.1. Get a single field

public Field getField(String name); :

public Field getDeclaredField(String name);

Name Name of the field to be obtained

4.7.2. Get all fields

public Field[];

getFields() ;

public Field[] getDeclaredFields();

@Test
public void testField(a) throws Exception {
    // 1 gets the bytecode object
    Class clz = Person.class;
    Object obj = clz.newInstance();
    // 2 Get the field
    Field[] fs = clz.getFields();
    for(Field f: fs){
        System.out.println(f);
    }
    Field[] fs2 = clz.getDeclaredFields();
    for(Field f: fs2){
        System.out.println(f);
    }
    // Get a single field
    Field nameField = clz.getDeclaredField("name");
    System.out.println(nameField);
}
Copy the code

4.8. Operation Field

get(Object obj);

set(Object obj,Object value);

// Make private fields accessible
nameField.setAccessible(true);
// Manipulate the name field
// Set the data for that field
nameField.set(obj,"Little Wolf");
// Get the name field data
Object nameValue = nameField.get(obj);
System.out.println(nameValue);
Copy the code

Five, the introspection

5.1, JavaBean

Javabeans are one of the most important reusable components in Java (reduce code duplication, reuse, encapsulate business logic, encapsulate data).

5.1.1 JavaBean specification requirements

  1. Use the public modifier.
  2. Privatize fields.
  3. Provide get/set methods.
  4. Public no-argument constructor (using reflection, using bytecode objects. NewInstance to create objects).

5.1.2 Three members

  1. The event
  2. methods
  3. attribute

5.1.3 What are attributes

Javabeans can encapsulate data by storing it in properties of a bean object.

Properties are not fields; they are derived using get/set methods.

** Standard get methods/get methods/read methods: **public modifier, no arguments, return, get start.

** Standard set method/set method/write method: **public modifier, parameter, no return, set start.

Note:

  1. As long as it is a standard GET /set method, there are attributes, not necessarily written in a specification automatically generated by the tool.

  1. The fields are Boolean, and the read method does not start with GET, but with is.

5.2 overview of introspection

A JavaBean is a very common component that is nothing more than a property inside an operation. So SUN provides an API for manipulating JavaBean properties: Introspector.

5.3. The role of introspection

  1. Obtain the related state information, such as the attribute name and type.
  2. Gets the value of the corresponding accessor to the property.

5.4. Introspect common apis

  1. Through the bytecode object, the description object of the JavaBean is obtained and the description object of the JavaBean is returned

    public static BeanInfo getBeanInfo(Class beanClass, Class stopClass);

  2. Get the property descriptor from the JavaBean description object

    PropertyDescriptor[] getPropertyDescriptors();

  3. From the property descriptor, you get the property name, property type, getter/setter methods

    Public String getName();

    Get attribute type: public Class
    getPropertyType();

    Getmethod: public Method getReadMethod();

    Public Method getWriteMethod();

When retrieving a BeanInfo object from a bytecode object, the default is to introspect information about the current bytecode object and all of its parent classes. For example, getBeanInfo(a.class) will also introspect information about A’s parent class, such as Object. In general, we don’t care about the attributes of the parent class, so we can call the overloaded getBeanInfo method: getBeanInfo(beanClass,stopClass).

Demonstration: BeanInfo BeanInfo = Introspector. GetBeanInfo (Person. Class and Object. The class).

package com.day03.IntrospectorDemo;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/ * * *@author Xiao_Lin
 * @date2020/12/29 13:37 * /
public class TestIntrospector {

  public static void main(String[] args) throws Exception {
    // Create an object
    Student student = Student.class.newInstance();
    // Convert javabeans to beanInfo
    BeanInfo beanInfo = Introspector.getBeanInfo(student.getClass(),Object.class);
    // Get all attributes from beanInfo
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // Walk through the property descriptor array to get each property descriptor
    for (PropertyDescriptor pd : propertyDescriptors) {
      // Get the attribute name
      System.out.println("Attribute name =" + pd.getName());
      // Get the attribute type
      System.out.println("Attribute type =" + pd.getPropertyType());
      // Get the getter/setter method for the property
      Method getMethod = pd.getReadMethod();
      System.out.println("Get method =" +getMethod);
      Method setMethod = pd.getWriteMethod();
      System.out.println("Set method =" +setMethod);
      // Call the set method of the age attribute
      if ("age".equals(pd.getName())){
        // Execute the set method of age. The invoke parameter means to assign which value to which object
        setMethod.invoke(student,22);
      }
      // Execute the get method againSystem.out.println(student.getAge()); }}}Copy the code

5.5. Transformation between Javabeans and Maps

Maps and Javabeans have similar structures. We can convert them to each other. Map the key to the attribute name 1-1

5.5.1 Switch from JavaBean to Map

 / / Javabean map
  public static Map<String, Object> BeanToMap(Object obj) throws Exception{
    Map<String, Object> map = new HashMap<>();
    // Get all attributes through introspection
    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass(), Object.class);
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
      // Get the attribute name as key
      String key = pd.getName();
      // Get the getter method for the property and call
      Object value = pd.getReadMethod().invoke(obj);
      map.put(key, value);
    }
    return map;
  }

Copy the code
public class BeanMap {

  public static void main(String[] args) throws Exception{
    Map<String, Object> map = BeanToMap(new Student("Zhang".20));
    map.forEach((k,v)-> System.out.println(k+"- >"+v)); }}Copy the code

5.5.2 Converting Map to JavaBean

// Map to JaveBean, where generics are used
  public static <T> T  MapToBean(Map<String, Object> map ,Class<T> clz) throws Exception{
    // Create a JavaBean object
    T t = clz.newInstance();
    // Iterate over the property, get the property name as the MAO key to get the value, and set it to the setter method
    // Get all attributes
    BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
      String key = pd.getName();
      Object value = map.get(key);
      pd.getWriteMethod().invoke(t,value);
    }
    return t;
  }
Copy the code

Six, annotations,

6.1 Introduction of annotations

We can use annotations to modify member information in a class. Annotations are really annotations.

6.2. Define the format

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interfaceAnnotation name {}Copy the code

Definition format: @interface Annotation name

Use format: @ Annotation name (attribute name = attribute value, attribute name = attribute value)

Annotations are attached to program elements, and in order to have certain functions, three roles must participate:

  1. Annotation itself
  2. The pasted program element
  3. Third party programs that use reflection to give annotations functions (there must be some code behind annotations that gives annotations functions).

6.3. Built-in annotations

  • @OverrideQualify overriding superclass methods
  • @DeprecatedThe tag is outdated and not recommended. Prior to JDK5, document comments were used to mark obsolescence
  • @SuppressWaringsSuppress warnings issued by the compiler
  • @FunctionallnterfaceMark this interface as a functional interface (starting with JDK1.8)

6.4. Meta-annotations

Annotation: A tag attached to a class/method/variable, etc. that can be used by third party programs to give functionality.

Meta-note: a note attached to a note when defining a note, used to define its use. He includes three notes

6.4.1,@Target

Indicates where an annotation can be pasted (on a class, method, constructor, etc.). Constants for the position are encapsulated in the ElementType enumeration class.

  • ElementType.ANNOTATION_TYPEOnly classes can be decorated.
  • ElementType.CONSTRUCTOROnly constructors can be decorated.
  • ElementType.FIELDOnly fields (attributes) can be decorated, including enumerated constants.
  • ElementType.LOCAL_VARIABLEOnly local variables can be modified.
  • ElementType.METHODOnly methods can be decorated.
  • ElementType.PACKAGEOnly packages can be decorated.
  • ElementType.PARAMETEROnly parameters can be decorated.
  • ElementType.TYPEYou can only modify classes, interfaces, and enumerations.

6.4.2,@Retention

Represents the period in which the annotation can be stored, and represents the value of the period, encapsulated in the RetentionPolicy enumeration class.

6.4.3, @ Documented

Labels marked with @Documented will be saved to the API document.

6.4.4, @ Inherited

Inherited Tags can be Inherited by child classes.

The tag is outdated and not recommended. Prior to JDK5, document comments were used to mark obsolescence

  • @SuppressWaringsSuppress warnings issued by the compiler
  • @FunctionallnterfaceMark this interface as a functional interface (starting with JDK1.8)