Java basics-explain Java reflection mechanism (Reflective)

Overview

Reflection refers to a program capable of analyzing class capabilities, also called introspection capability at program runtime, and is mainly used for the construction of tool programs, not applications.
The role of the reflection mechanism includes the following four points:

  1. Runtime analysis class
  2. View objects at runtime
  3. Implement general array operations
  4. Use Method

Java's reflection mechanism is mainly implemented through the following classes: Class, Constructor

Related classes and methods

Class

Class (a class that represents a type, is actually a generic class, but you can ignore the type parameter and use the original Class directly): How to get the Class object? It can be obtained by any Java type (or void) class method, or by the object's getClass method.

Common methods include:

  1. getName
  2. forName-static factory method to get the Class object corresponding to the specified class name
  3. newInstance-get an object of type Class
  4. getFields, getMethods, getConstructor (public fields or methods)
  5. getDeclaredFie1ds, getDeclareMethods, getDeclaredConstructors (all fields or methods, but not inherited)

Field、Method、Constructor

General method

  1. getName
  2. getModifiers–Modifier.toString
  3. setAccessible-can modify the access restrictions of members at runtime

Field

  1. getType
  2. get、set

Method

  1. invoke

The typical example of the application in "Java Core Technology-Volume One" is to use the reflection mechanism to parse and print the members of the class. The code example is as follows:

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;

/**
 * @description: this program uses reflection to print all features of a class
 * @author: lyg89
 * @create: 2019-03-23 23:10
 **/
public class ReflectionTest {

    public static void main(String[] args) {
        String name;
        if (args.length > 0) {
            name = args[0];
        } else {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter class name (e.g. java.util.Date):");
            name = scanner.next();
        }

        try {
            Class<?> aClass = Class.forName(name);
            String modifiers = Modifier.toString(aClass.getModifiers());
            if (modifiers.length() > 0) {
                System.out.print(modifiers + " ");
            }
            System.out.print("class " + name);

            Class<?> superclass = aClass.getSuperclass();
            if (superclass != null && superclass != Object.class) {
                System.out.print(" extends " + superclass.getName());
            }

            System.out.print("\n{\n");
            printConstructors(aClass);
            System.out.println();
            printMethods(aClass);
            System.out.println();
            printFields(aClass);
            System.out.println("}");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    private static void printConstructors(Class clazz) {

        Constructor[] constructors = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.print("    ");
            int modifiers = constructor.getModifiers();
            String strModifier = Modifier.toString(modifiers);
            if (strModifier.length() > 0) {
                System.out.print(strModifier + " ");
            }
            System.out.print(clazz.getName() + " (");

            Class[] parameterTypes = constructor.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                if (i > 0) {
                    System.out.print(", ");
                }
                System.out.print(parameterTypes[i].getName());
            }
            System.out.println(");");
        }
    }

    private static void printMethods(Class clazz) {
        for (Method method : clazz.getMethods()) {
            System.out.print("    ");
            int modifiers = method.getModifiers();
            String strModifier = Modifier.toString(modifiers);
            if (strModifier.length() > 0) {
                System.out.print(strModifier + " ");
            }

            Class<?> returnType = method.getReturnType();
            System.out.print(returnType.getName() + " " + method.getName() + " (");

            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                if (i > 0) {
                    System.out.print(", ");
                }
                System.out.print(parameterTypes[i].getName());
            }
            System.out.println(");");
        }
    }

    private static void printFields(Class clazz) {
        for (Field field : clazz.getFields()) {
            System.out.print("    ");
            int modifiers = field.getModifiers();
            String strModifier = Modifier.toString(modifiers);
            if (strModifier.length() > 0) {
                System.out.print(strModifier + " ");
            }
            System.out.println(field.getType().getName() + " " + field.getName() + ";");
        }
    }
}

summary

The reflection mechanism helps us to access the meta information of the program when the program is running, including Java types, objects, methods, etc., and can dynamically create objects, and even modify the access control restrictions of the objects, but the module mechanism in Java 9 has begun to setAccessible has some limitations. Using the reflection mechanism, we can construct a powerful tool set, so it is used in many frameworks. It can be said that understanding reflection, we will have a deeper understanding of the flexibility sought by the design of the program.

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/88937414