This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

Lucky draw instructions at the end of the article oh!

What is reflection

Reflection mechanism refers to the fact that the program can obtain information about itself at run time, that is, dynamically load classes and obtain class details while the program is running to manipulate the properties and methods of classes or objects. Essentially, the JVM takes a class object and decompiles it to get information about it. Reflection, one of the characteristics of Java, is a mechanism for indirectly manipulating target objects.

The basic class of reflection

The Class Class is the basis for reflection implementation, and to understand reflection, you first need to understand the Class Class. During the execution of the program, the virtual machine maintains a type identifier called the runtime for all objects. This information keeps track of the complete structure of the class to which each object belongs, including package name, class name, implemented interface, owned methods, and fields. You can access this information through a special Java class, the Clas class. A Class object is called a type object of a Class. Each Class object corresponds to a.class file loaded into the JVM.

public final class Class<T> implements java.io.Serializable, GenericDeclaration, Type, AnnotatedElement { private static final int ANNOTATION= 0x00002000; private static final int ENUM = 0x00004000; private static final int SYNTHETIC = 0x00001000; private static native void registerNatives(); static { registerNatives(); }... }Copy the code

The JVM first compiles the code into a. Class bytecode file, which is loaded into the JVM’s memory by the class Loader, and creates a class object to store in the heap (note that this is not the new object, but the class object). Before creating a Class object, the JVM checks whether the Class is loaded, looks for the corresponding Class object, allocates memory for it, and then initializes it.

After loading a Class, the method area in the heap produces a Class object that contains the complete structure of the Class. The Class object is used to view the structure of the Class, like a mirror. That’s why it’s called reflection. For more on class loading, see the previous article: THE JVM Series: Class loading Mechanisms

Basic use of reflection

Common classes for reflection mechanisms

Java.lang.Class; 

Java.lang.reflect.Constructor;  

Java.lang.reflect.Field;

Java.lang.reflect.Method; 

Java.lang.reflect.Modifier;

Reflect common apis

Object. SetAccessible (true);

Class:

Get public property: getField(” property name “);

Get private property: getDeclaredField(” property name “);

GetMethod (” method name “, null); getMethod(” method name “, null);

Get all public method objects: getMethods();

Get all method objects: getDeclaredMethods();

GetDeclaredMethod (” method name “, type of method parameter……) ;

The call exposes parameterized constructs: getConstructor(constructs parameter types);

Call private parameter constructs: getDeclaredConstructor(constructs parameter types);

Check if it is an instance of a class: isInstance(obj);

The Field:

Get the attribute name: getName();

Get the type of the attribute: getType();

Get property modifiers: getModifiers();

1: Set (obj,obj);

Method:

Invoke (class instantiation object, array of method arguments); // Execute method

The Constructor:

NewInstance(); // Get an instance of the class by constructing it

Here’s the code:

public class Test(){ A a=new A(); Class c1=A.class; // Every class has an implicit static member variable class c2= a.goetclass (); Class c3 = null; getClass = null; try { c3 = Class.forName("com.xxxx.A"); Catch (ClassNotFoundException e) {e.printstackTrace ();} catch (ClassNotFoundException e) {e.printstackTrace (); } } class A{}Copy the code

Method reflection: getName

The getName method prints out the class name of the class type.

public class Test2 { public static void main(String[] args) { Class c1 = String.class; Class c2 = void. Class; System.out.println(c1.getName()); System.out.println(c2.getName()); }}Copy the code

Member variable reflection

public class TestUtil {
    public static void printFieldMessage(Object obj){
        Class c = obj.getClass();
        //Field[] fs = c.getFields();
    }
Copy the code

The getFields() method gets information about all public member variables. And the reflection of the method where the public member variables, there is also a get all self-declared member variables information: Field[] fs = c.getdeclaredfields (), then iterated to get the result as follows:

For (Field Field: fs) {Class fieldType = field.getType(); String typeName = fieldType.getName(); String fieldName = field.getName(); System.out.println(typeName+" "+fieldName); }Copy the code

Constructor reflection

public static void Test(Object obj){ Class c = obj.getClass(); /* * Java.lang. Constructor encapsulates Constructor information, which has two methods: GetConstructors () gets all public constructors * getDeclaredConstructors() gets all self-declared constructors */ //Constructor[] cs = c.getConstructors(); Constructor[] cs = c.getDeclaredConstructors(); for (Constructor constructor : cs) { System.out.print(constructor.getName()+"("); / / get the constructor argument list - > parameter list of Class type Class [] paramTypes = constructor. GetParameterTypes (); for (Class class1 : paramTypes) { System.out.print(class1.getName()+","); } System.out.println(")"); }}Copy the code

conclusion

Reflection is not used much in real programming, but many designs are related to reflection mechanisms, such as dynamic proxies, JDBC connecting to databases, and the Spring/Hibernate framework (in fact, reflection is related because of the use of dynamic proxies).

Draw that

1. This event is supported by the Nuggets official details can be found at juejin.cn/post/701221…

2. You can participate by commenting on the article. The more you comment, the more chance you have to win the prize.

3. This month’s articles will participate in the lucky draw, welcome more interaction!

4. In addition to the official lottery of nuggets, I will also give peripheral gifts (one mug and several nuggets badges, mugs will be given to fans, badges will be randomly selected, the number of badges will increase according to the number of comments).