This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

preface

Reflection is important in Java content and is part of the reason why Java is known as a quasi-dynamic language.

Dynamic languages: Languages that determine data types at run time. A variable does not require a type declaration before it is used; the type of a variable is usually the type of the value to which it is assigned.

Static languages: A language that determines the data type of a variable at compile time. Most statically typed languages require that the data type be declared before a variable can be used.

What is reflection?

A program that analyzes the capabilities of a class is called reflection — Java Core Technology

In simple terms, after a Class load is performed, there is a Class object in the heap that holds the information about the Class

The phenomenon of loading a class with some structural information that looks like itself in a mirror is called reflection

The role of reflex mechanisms

  1. The ability to analyze classes at run time
  2. Examine objects at run time
  3. Implementation of generic array operation code
  4. Use objects like Method

Let’s take it one at a time

1. Leverage the capabilities of reflection analysis classes

In the java.lang.reflect package there are three Field, Method, and Constructor classes that describe class member variables, methods, and constructors, respectively

And we’ve seen before that these classes appear in Class objects that appear in Class loads

So by providing Class objects, we can learn a lot about the corresponding classes.

@SuppressWarnings({"all"})
public class Test01 {
    public static void main(String[] args) throws NoSuchMethodException,NoSuchFieldException {
        Cat cat = new Cat();
        Class aClass = cat.getClass();

        // Get the array of method objects in aClass that correspond to the methods in Cat
        Method[] methods = aClass.getMethods();
        // Provide the method name to get the corresponding method object
        Method method = aClass.getMethod("CarName");

        // Get the array of fields corresponding to the fields in the Cat class
        Field[] fields = aClass.getFields();
        // Provide the field name to get the corresponding field object
        Field age = aClass.getField("age");

        // Get the array of constructors corresponding to the Cat constructors in aClass
        Constructor[] constructors = aClass.getConstructors();
        To get the specified constructor, pass in the Class object of the corresponding object's Class
        Constructor constructor = aClass.getConstructor(String.class, int.class);
        /** * public Cat(String name, int age) { * this.name = name; * this.age = age; *} * /}}Copy the code

2. Examine objects at run time using reflection

Also use the Class object to get information about the Class at run time and perform certain operations (such as creating a toString method for all classes).

 
   public class test1 {

    private String name = "test";
    private int age = 12;
    private String home = "home";
    
    
    public void mms (a){
        System.out.println("Mod");
    }
    public String toString(a)
    {
        Field[] fields=this.getClass().getDeclaredFields();
        StringBuffer strBuf=new StringBuffer();
        strBuf.append(this.getClass().getName());
        strBuf.append("[");
        for(int i=0; i<fields.length; i++) { Field fd=fields[i]; strBuf.append(fd.getName()+":");
            try
            {
                strBuf.append(fd.get(this));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            if(i! =fields.length-1)
                strBuf.append("|");
        }

        strBuf.append("]");
        returnstrBuf.toString(); }}Copy the code

3. Use reflection mechanism to implement generic array operation code

The java.Reflect. Array class allows arrays to be created dynamically, so you can do things like expand an Array using array.copyof

public class test2 {
    private static int[] tmp = {1.2};
    public static int[] add(int[] num, int newLength){
        // Get the array Class object
        Class<? extends int[]> aClass = tmp.getClass();
        // Check whether it is an array class
        if(! aClass.isArray()){ System.out.println("Not an array.");
            return null;
        }
        else {
            // The object representing the array class defines the class and determines the correct type of the arrayClass<? > componentType = aClass.getComponentType();int length = Array.getLength(tmp);
            // Create new array
            Object o = Array.newInstance(componentType, newLength);
            return (int[]) o; }}public static void main(String[] args) {
        System.out.println(tmp.length);
        int[] add = add(tmp, 5); System.out.println(add.length); }}Copy the code

4. Invoke methods using objects such as Method

Reflection lets you call a Method by getting a Method object from a Class object

The previous call was an object. Methods (e.g. Cat.carname ())

Invoke (object)(e.g. Carname.invoke (o))

public class Test4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // Load classes dynamically through reflection
        Class aClass = Class.forName("reflex.testclass.Cat");

        // Get the specified method object by the method name
        Method carName = aClass.getMethod("CarName");

        // Create instance objects through newInstance (using the no-parameter constructor)
        Object o = aClass.newInstance();

        // Execute the Method through the Method call
        String invoke = (String) carName.invoke(o);

        // Outputs the return valueSystem.out.println(invoke); }}Copy the code