A brief introduction to reflection mechanism

Before we dive into Java’s reflection mechanism, let’s take a quick look at Java class loading.

1. Class loading overview

When a program wants to use a class that has not been loaded into memory, the system will load, connect, and initialize the three steps to achieve the initialization of the class.

Loading time

  • Create an instance of the class
  • Access a static variable of a class or assign a value to a static variable
  • Call a static method of a class
  • Use reflection to force the creation of a java.lang.Class object corresponding to a Class or interface
  • Initialize the subclass
  • Or run the main class directly with java.exe

2. Reflection overview

  • Java reflection mechanism is in the running state, for any class, can get all the attributes and methods of this class, for any object, can call any method or any attribute, this dynamic access to information and call object method is Java reflection mechanism. To dissect a Class, it is necessary to obtain the bytecode file object of the Class first. Methods and attributes of the Class are obtained through the methods of the Class Class. Therefore, the object of the Class file is created first for operation.

3, get class object method

There are three ways to get an object of type class

1. Use the forName method of the class class to get the class object

Class clazz = class.forname ("Object");Copy the code

2. Use the.class method to get the class object

Class clazz = object.class;Copy the code

3. Use the.getClass() method of the existing object to obtain the Class object

Object obj = new Object(); Class clazz = obj.getClass();Copy the code

There are three ways to get a Class object