Phase to recommend

  • Java Basics
  • Java concurrent programming
  • JVM

Java Reflection concept

Reflection mechanism: refers to the process of running a program, any class can obtain all its attributes and methods, and any object can call any method. This ability to dynamically retrieve information about classes and objects, as well as dynamically invoke methods of objects, is known as the Reflection mechanism of the Java language.

Why we need reflection

Many objects in Java programs have two types at run time: compile-time type and runtime type. The type at compile time is determined by the type used to declare the object, and the type at run time is determined by the type actually assigned to the object at run time. To solve these problems, the program needs to discover real information about objects and classes at run time, and reflection must be used to retrieve information about objects and classes at run time.

Java reflection usage

Reflection using steps

1. Get the Class object of the Class you want to operate on. This Class object is the core of reflection and can call any method of the Class.

2. Call the method defined in the corresponding Class object. This is the use phase of reflection.

3. Use the reflection API to get and call information about class properties and methods.

Three ways to get a Class object

  • Calling an objectGetClass ()Method to get the corresponding Class object of the Class:
Person p = new Person();
Class clazz = p.getClass();
Copy the code
  • To call a classThe class attributeTo get the corresponding Class object of this Class:
Class clazz = Person.class;
Copy the code
  • Call the ClassClass.forname ()Static method to obtain the corresponding Class object of the Class, which is the safest and best performance method:
Class clazz=Class.forName("fullClassPath");
//fullClassPath is the package path and name of the class (most commonly used)
Copy the code

Once we have the Class object of the Class we want to manipulate, we can retrieve and view the methods and properties in the Class through the methods in the Class.

// Get the Class object of the Person Class
Class class=Class.forName("reflection.Person");

// Get all method information for the Programmer class
Method[] method=class.getDeclaredMethods();


// Get all member attributes of the Programmer class
Field[] field=class.getDeclaredFields();


// Get all constructor information for the Programmer class
Constructor[] constructor=class.getDeclaredConstructors();

Copy the code

There are two ways to create objects through reflection

  • Class object callnewInstance()methods

Use the newInstance() method of the Class object to create instances of the corresponding Class, but this method requires that the corresponding Class have a default empty constructor.

  • Constructor callnewInstance()methods

Use the Class object to get the specified Constructor object and then call the Constructor’s newInstance() method to create an instance of the corresponding Class of the Class object. This method creates instances by selecting the Constructor.

// Get the Class object of the Programmer Class

Class class=Class.forName("reflection.Person");

// Use the newInstane method to create an object

Programmer p=(Person) clazz.newInstance();

// Get the constructor and create the object
Constructor c=class.getDeclaredConstructor(String.class,String.class,Integer.class);

// Create an object and set its properties
Programmer p1=(Person) c.newInstance("Akiang"."Male".20);

Copy the code

The Java reflection API

  1. Class: Reflection core Class, which is generated by the JVM and can be used to see the structure of the entire Class, such as properties, methods, and so on.

    Common methods of Class:

The method name instructions
forName() (1) Get a reference to a Class object, but the referenced Class was loaded before it was loaded (the first object of the Class was not generated).
(2) To generate a Class reference, forName() is initialized immediately.
Object-getClass() Gets a reference to a Class object, returning a Class reference representing the actual type of the object.
getName() Take the fully qualified class name (including the package name), that is, the full name of the class.
getSimpleName() Get class name (excluding package name)
isInterface() Determines whether the Class object represents an interface
getInterfaces() Returns an array of Class objects representing all interfaces implemented by the classes referenced by the Class object.
getSuperclass() Returns a Class object representing the immediate base Class inherited by the Class referenced by the Class object. This method can be used to discover the complete inheritance structure of an object at run time.
newInstance() Returning an Oject object is one way to implement a “virtual constructor.” Classes created using this method must have a constructor with no arguments.
getFields() Gets all public fields of a class, including all public fields inherited from the parent class. Similar examples are getMethods and getConstructors.
getDeclaredFields() Get the self-declared fields of a class, that is, public, private, and proteced, default but not any fields declared by the parent class. Similar examples are getDeclaredMethods and getDeclaredConstructors.
  1. Constructor Class: Found in the reflection package (java.lang.Reflect), which reflects the Class Constructor represented by the Class object.

    The main methods of the Class Class associated with Constructor are as follows:

Method return value Method names Method statement
static Class<? > forName(String className) Returns the Class object associated with the Class or interface with the given string name.
Constructor getConstructor(Class<? >… parameterTypes) Returns a constructor object with public access for the specified argument type
Constructor<? > [] getConstructors() Returns an array of Constructor objects for all constructors that have public access
Constructor getDeclaredConstructor(Class<? >… parameterTypes) Returns constructor objects of the specified parameter type, all declared (including private)
Constructor<? > [] getDeclaredConstructor() Returns all declared (including private) constructor objects
T newInstance() Call the no-argument constructor to create a new instance of the Class represented by this Class object.
  1. Field class: a class in the java.lang. reflec package that describes attributes in a class, including their names, data types, access modifiers, and so on, and can be used to get and set values for attributes in the class.

    The Class and Field methods are as follows:

Method return value Method names Method statement
Field getDeclaredField(String name) Gets the (including private) field of the specified name, excluding inherited fields
Field[] getDeclaredField() Gets all (including private) fields of the Class or interface represented by the Class object, excluding inherited fields
Field getField(String name) Gets a public decorated field with the specified name, including inherited fields
Field[] getField() Gets the field whose modifier is public, containing the inherited field
void set(Object obj, Object value) Sets the Field represented by this Field object on the specified object variable to the specified new value.
Object get(Object obj) Returns the value of the Field represented by this Field on the specified object
Class<? > getType() Returns a Class object that identifies the declared type of the Field represented by the Field object.
boolean isEnumConstant() Returns true if this field represents an element of enumerated type; Otherwise return false
String toGenericString() Returns a string that describes the Field, including its generic type
String getName() Returns the name of the Field represented by this Field object
Class<? > getDeclaringClass() Returns a Class object representing a Class or interface that declares the fields represented by this Field object
void setAccessible(boolean flag) Set the accessible flag of this object to the indicated Boolean value, that is, to make it accessible
  1. Method class: a class in the java.lang.reflec package that represents a Method of the class. It can be used to retrieve information about a Method in the class (including return value types, Method parameters, etc.) or to execute a Method (the Method in the class can be invoked via the invoke() Method of the Method object).

    The Class gets the methods associated with the Method object:

Method return value Method names Method statement
Method getDeclaredMethod(String name, Class<? >… parameterTypes) Returns a Method object with the specified argument that reflects the specified declared Method of the Class or interface represented by this Class object.
Method[] getDeclaredMethod() Returns an array of Method objects that reflect all methods declared by the Class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but not inherited methods.
Method getMethod(String name, Class<? >… parameterTypes) Returns a Method object that reflects the specified public member methods of the Class or interface represented by this Class object.
Method[] getMethods() Returns an array of Method objects that reflect the public member methods of the Class or interface represented by this Class object (including those declared by the Class or interface and those inherited from superclasses and superinterfaces).

Java reflection call flow

  • Reflection class and reflection method are obtained by searching through the list to find matching methods, so the search performance will vary with the size of the class method;

  • Each Class has a corresponding Class instance, so each Class can take the method () reflection method and apply it to other instances;

  • Reflection is also considered thread-safe, safe to use;

  • Reflection uses soft reference relectionData to cache class information, avoiding the overhead of retrieving it from the JVM each time.

  • Reflection calls generate a new proxy Accessor multiple times, while bytecode survival allows for offloading, so a separate class loader is used.

  • When a method is found, it is copied instead of using the original instance to ensure data isolation.

  • Scheduling the reflection method, which is ultimately executed by the JVM invoke0();

🏁 the above is a brief introduction to Java reflection. If there are any mistakes, please leave a comment. If you think this article is helpful, please give a thumbs up to 👍