Reflection analysis of JAVA basic knowledge

Three problems

What is reflection? What can reflection be used for? In which scenarios is reflection used and how?

The program that can analyze the ability is called reflection!

Reflection mechanism can be used

1. The ability to analyze classes at runtime.

2. View the object at runtime, for example: write a toString() method for all classes to use (reflection can get all variables, private can also be obtained).

3. Realize general array operation code.

4. Use the Method object, which is very similar to the function pointer in C++.

Programs that dynamically manipulate Java code are widely used in JavaBeans and in development tools. For example, the prompts that appear after the object point are implemented by reflection.

 

During the running of the program, the Java runtime system always maintains a type identification called runtime for all objects.

This information tracks the class to which each object belongs, and the virtual machine uses the runtime type information to select the corresponding method to execute,

The class that stores this information is called Class.

The getClass() method in the Object class will return an instance of the Class type.

The most commonly used Class method is getName, which will return the full path name of the class.

Call the static method forName() to get the Class object corresponding to the class name.

Class class=Class.forName("com.xx.xxx");

The Class class is actually a generic class, which complicates the already abstract concept.

In most practical problems, you can ignore the type parameter and use the original Class class.

The newInstance() method can be used to dynamically create an instance of a class.

It calls the no-argument constructor by default to create an instance, if there is no default constructor it will throw an exception!

Use reflection to analyze the structure of a class, and use Field, Method, and Constructor to describe the domain, method, and constructor of the class, respectively.

All three classes have a method called getName(), which returns the name of the item.

The Field class has a getType() method to return a Class object describing the type of the field.

The Method and Constructor classes have methods that can report the types of parameters, which will return an integer value and use different bit switches to describe the public static modifier.

There are isPublic, isPrivate, isFinal methods in the Modifier class to determine whether the constructor or constructor is public, private, or final. The toString() method can print out the modifier.

Here is a class, you can enter the full path name of the class already in Java to print out its methods.

package com.wavewave.demo.test;

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

/**
 * @author wavewave
 * @CreateDate: 2020/4/13 1:51 PM
 * @Description:
 * @Version: 1.0
 */
public class Test {

    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("请输入类名称");
            name = scanner.next();
        }

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

            if (superCl != null && superCl != Object.class) {
                System.out.print(" extends " + superCl.getName());
            }
            System.out.print("\n{\n");
            printConstructors(cl);
            System.out.println();
            printMethods(cl);
            System.out.println();
            printFields(cl);
            System.out.println("}");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    private static void printConstructors(Class cl) {
        Constructor[] constructors = cl.getDeclaredConstructors();
        for (Constructor c : constructors) {
            String name = c.getName();
            System.out.print("  ");
            String modifiers = Modifier.toString(c.getModifiers());
            if (modifiers.length() > 0) {
                System.out.print(modifiers + " ");
            }
            System.out.print(name + "(");

            Class[] parameterTypes = c.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 cl) {
        Method[] methods = cl.getDeclaredMethods();
        for (Method m : methods) {
            Class returnType = m.getReturnType();
            String name = m.getName();

            System.out.println("    ");
            String modifiers = Modifier.toString(m.getModifiers());
            if (modifiers.length() > 0) {
                System.out.print(modifiers + " ");
            }
            System.out.println(returnType.getName() + " " + name + "(");

            Class[] parameterTypes = m.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 cl) {
        Field[] fields = cl.getDeclaredFields();
        for (Field f : fields) {
            Class type = f.getType();
            String name = f.getName();
            System.out.print("  ");
            String modifiers = Modifier.toString(f.getModifiers());
            if (modifiers.length() > 0) {
                System.out.print(modifiers + " ");
            }
            System.out.print(type.getName() + " " + name + ";");
        }
    }

}

You can try it out!

Guess you like

Origin blog.csdn.net/Small_Wave_Wave/article/details/105485479