The interview for Java development position was asked what to do with reflection

  • 2021-11-01 03:13:23
  • OfStack

What exactly is reflection in a directory? ? ? 2. Life cycle of class 3. Java reflection framework mainly provides the following functions: basic usage of reflection 1. Obtaining Class object 2. Judging whether it is a real class of a class 3. Creating instance 4. Obtaining constructor information 5. Obtaining method 6. Obtaining member variable (field) information of class 7. Precautions for creating array reflection using reflection Summary of main uses of reflection

What exactly is reflection? ? ?

The core of reflection is that JVM dynamically loads classes or calls methods and accesses properties at runtime, and it does not need to know who the running object is in advance (at code writing or compile time).

Each class produces a corresponding Class object, which is stored in the. class file.

All classes are dynamically loaded into JVM when they are used for the first time. When the program creates a reference to a static member of the class, the class will be loaded. Class objects will only be loaded when needed. static initialization is carried out when the class is loaded.


public class TestMain {
    public static void main(String[] args) {
        System.out.println(Test.name); //  Right Test Static members of the class name Quote. 
    }
}
class Test {
    public static String name = "Test Name";
    static {
        System.out.println("Test Static block ");
    }
    public Test() {
        System.out.println("Test Constructed ");
    }
}

Output:

Test Static Block Test Name

2. Lifecycle of a class

After a class is compiled, the next step is to start using the class. How to use it?

After the class is compiled, the class is used. In the program execution, JVM is completed through three steps: loading, linking and initialization.

1. Loading: Completed by the class loader, find the corresponding bytecode, and create an Class object.

The class loader first checks whether the class's Class object has been loaded, and if not, the default class loader looks for the corresponding. class file based on the class name.

The loader loads the binary file of the. class file into the method area of JVM, and creates an java. lang. Class object describing the class in the heap area to encapsulate the data, but the same class is only loaded once by the class loader.

2. Link: Is to assemble binary data into a runnable state

Verification: 1 is used to confirm whether this binary file is suitable for the current JVM (version)

Prepare: Allocate memory space for static members and set default values.

Parsing: The process of converting the code in the constant pool as a direct reference until all symbols can be used by the running program (establishing a complete correspondence) to verify the bytecode in the class and allocate space for the static domain.

3. Initialization: If the class has a parent, initialize it, executing static initializers and static initialization blocks.

3. The Java reflective framework mainly provides the following functions:

Construct objects of any 1 class at run time

Call the method of any 1 object at run time

Determine the class to which any 1 object belongs at run time

Determine the member variables and methods of any 1 class at run time (even the private method can be called through reflection)

Basic Usage of Reflection

1. Get the Class object

< 1 > forName static methods using the Class class:


public static Class<?> forName(String className) 
 In JDBC This method is often used to load database drivers in development : Class.forName(driver);
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting 

< 2 > Get the class of a 1 object directly: (known type name or known object at compile time)


Class<?> klass = int.class;
Class<?> classInt = Integer.TYPE;

< 3 > Invoke the getClass () method of an object:


StringBuilder str = new StringBuilder("123");
Class<?> klass = str.getClass();

Note: When you use. class to create a reference to an Class object, the Class object is not automatically initialized; Using forName (...) automatically initializes the Class object.

2. Determine whether it is a real class of a class

1: Judge with instanceof keyword

Reflection: isInstance () method of Class object in reflection

public native boolean isInstance(Object obj);

3. Create an instance

There are two main ways to generate objects through reflection:

< 1 > Use the newInstance () method of the Class object to create an instance of the class corresponding to the Class object.


Class<?> c = String.class;
Object str = c.newInstance();

< 2 > The specified Constructor object is obtained through the Class object, and then the newInstance () method of the Constructor object is called to create an instance.


//  Get String Corresponding to Class Object 
Class<?> c = String.class;
//  Get String Band-like 1 A String Parameter constructor 
Constructor constructor = c.getConstructor(String.class);
//  Create an instance from the constructor 
Object obj = constructor.newInstance("23333");
System.out.println(obj);

4. Get constructor information

One instance of Constructor is obtained by getConstructor method of Class, and one newInstance method of Constructor can create one object instance

5. Get the method

< 1 > getDeclaredMethods() Returns all methods declared by a class or interface, including public, protected, default (package) access, and private methods, but excluding inherited methods


public Method[] getDeclaredMethods() throws SecurityException

< 2 > getMethods() Returns all public (public) methods of a class, including inherited public methods


public Method[] getMethods() throws SecurityException

< 3 > getDeclaredMethod() Returns a specific method, where the first parameter is the method name and the next parameter is the Class object corresponding to the parameter type of the method


public Method getDeclaredMethod(String name, Class<?>... parameterTypes)

< 4 > getMethod() Returns a specific method, where the first parameter is the method name and the next parameter is the Class object corresponding to the parameter type of the method


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

6. Get member variable (field) information for a class

getDeclaredFields() Access all declared member variables, but not inherited member variables.

getFileds() Access all declared public (public) member variables, including inherited public member variables.

getDeclaredField() Specific access to all member variables (excluding inherited ones), with the name of the member variable as the parameter.

getFiled() Specific access to public member variables (including inherited ones), with the name of the member variable as the parameter.

7. Create an array using reflection


public static Class<?> forName(String className) 
 In JDBC This method is often used to load database drivers in development : Class.forName(driver);
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting 
0

Where the Array class is java.lang.reflect.Array Class, we pass the getDeclaredMethods() 0 Create an array object, whose prototype is:


public static Class<?> forName(String className) 
 In JDBC This method is often used to load database drivers in development : Class.forName(driver);
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting 
1

The newArray () method is an Native method:


public static Class<?> forName(String className) 
 In JDBC This method is often used to load database drivers in development : Class.forName(driver);
// Join Java Develop and exchange samples: 7565848221 Blowing water and chatting 
2

Considerations for Reflection

Since reflection consumes an extra 1 set of system resources, there is no need to use reflection if you do not need to create an object dynamically. Permission checking can be ignored when a method is called by reflection, which may break the encapsulation and cause security problems.

Main uses of reflection

The most important use is to develop various common frameworks

Many frameworks (such as Spring) are configured (such as configuring JavaBean and Action through XML files). In order to ensure the universality of frameworks, they may need to load different objects or classes and call different methods according to the configuration files. At this time, reflection must be used-dynamically loading the objects to be loaded at runtime.

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: