SoFunction
Updated on 2025-04-14

Detailed explanation of the reflection mechanism in java

Detailed explanation of the reflection mechanism in java

Updated: March 31, 2025 09:43:50 Author: The Novice
The reflection mechanism in Java refers to the fact that Java programs can obtain all information about an object during operation. This article mainly introduces the relevant information about the reflection mechanism in Java. The code introduced in the article is very detailed. Friends who need it can refer to it.

1. What is reflection?

reflection(Reflection) is a Java programDuring operationofdynamicTechnology can beRuntime(runtime) Check and modify its own structure or behavior. Through reflection, the program can access, detect and modify its own members such as classes, objects, methods, properties, etc.

2. The purpose of reflection

  • Dynamic loading of classes: Programs can dynamically load classes in class libraries at runtime;
  • Dynamically create objects:Reflection can be based on class information, and the program can dynamically create object instances when it is run;
  • Calling methods:Reflection can be based on the method name, and the program can dynamically call the object's method when running (even if the method is not defined when writing the program)
  • Access member variables:Reflection can be based on the name of the member variable. The program can access and modify member variables at runtime (reflection can access private member variables)
  • Runtime type information:Reflection allows the program to query the type information of the object at runtime, which is very useful for writing common code and libraries;

Spring framework uses reflection to automatically assemble components to implement dependency injection;

The MyBatis framework uses reflection to create resultType objects and encapsulate data query results;

3. Get Class object

The first step in reflection is to obtainClassObject.ClassObjects represent metadata of a certain class and can be obtained in the following ways:

//Get Class type informationpublic class Text02 {
	public static void main(String[] args) throws ClassNotFoundException {
		//Method 1: By class name		Class stringClass1 = ;
		
		//Method 2: Pass the forName() method of the Class class		Class stringClass2 = ("");
		
		//Method 3: Call the getClass() method through the object		Class stringClass3 = "".getClass();
		
		(());//1604839423
		(());//1604839423
		(());//1604839423
	}

}

IV. Class type object usage scenario 1

Parses a JSON string into a Java object and outputs the field value of the object.

//Class type object usage scenario 1public class Text03 {
	public static void main(String[] args) {
		String json= "{\"name\":\"Chang'an lychee\",\"favCount\":234}";
		
		//Method definition		Document doc=(json,);
		(());
		(());
	}

}

useMethod parses the JSON string intoDocumentObject of class. During parsing, the data in the JSON string will be automatically mapped toDocumentin the corresponding field of the class.

5. Class type object usage scenario 2

passClassThe object obtains relevant information about a class at runtime, including class name, package name, member variable (field), member methods, etc.

//Class type object usage scenario 2//Get rich contentpublic class Text04 {
	public static void main(String[] args) throws ClassNotFoundException {
		Class clz = ("");
		
		//Get the class name		("Full Qualified Name:"+());
		("Simple class name:"+());
		
		//Get package name		("package"+().getName());
		();
		
		//Get member variable		Field[] fieldArray =();
		("Member variables(Fields)");
		for(Field field:fieldArray) {
			(field);
		}
		();
		
		//Get member method		Method[] methodArray = ();
		("Member Method");
		for(Method method:methodArray) {
			(method);
		}	
	}
}
  • ()Returns the fully qualified name of the class, including the package name, for example""
  • ()Returns the simple name of the class, excluding the package name, for example"HashMap"
  • ().getName()Returns the package name to which the class belongs, for example""
  • ()Return oneFieldArray, containing all fields declared by the class (including private fields).
  • ()Return oneMethodArray, containing all methods declared by the class (including private methods).

6. Create an object through reflection

Method 1: ByClassObjects are called directlynewInstance()method

Method 2: By obtaining the construction method (Constructor) to create an object.

//Create an object through reflectionpublic class Text05 {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		Class clz = (".");
		
		//Method 1: Directly use the Class object and call the newInstance() method		Object objx = ();//Equivalent to executing the parameterless construction method		
		//Method 2: Through the constructor (construction method)		//Construction method without parameters		Constructor constructor1 = ();//Get the parameterless constructor		(constructor1);
		Object obj1 = ();//Execute the constructor (construction method), create an object		
		//Grape construction method		Constructor constructor2 = ();//Get parameter constructor		(constructor2);
		Object obj2 = ("Fifteenth Day in Two Capitals");
		
		Constructor constructor3 = ();//Get parameter constructor		(constructor3);
		Object obj3 = (34);
		
		Constructor constructor4 = (,);//Get parameter constructor		(constructor4);
		Object obj4 = ("The wind blows on Longxi",64);
		
		(objx);
		(obj1);
		(obj2);
		(obj3);
		(obj4);
	}
  • newInstance()The method isClassAn object provides a method that calls the class's parameterless constructor to create an instance of the class.
  • Notice: This method has been deprecated after Java 9, so it is recommended to use itConstructorObject to create instances.
  • passgetDeclaredConstructor()Method ObtainDocumentThe parameterless constructor of the class, and then callnewInstance()Method creates an instance.
  • Notice: If there is no parameterless constructor in the class, callgetDeclaredConstructor()Will be thrownNoSuchMethodException
  • passgetDeclaredConstructor()Get with oneStringConstructing method of parameters and pass in"Fifteenth Day in Two Capitals"Create an object as a parameter.
  • passgetDeclaredConstructor()Get with oneintConstructing method of parameters and pass in34Create an object as a parameter.

7. Use the Java reflection mechanism to obtain and call the constructor of the class, access the private constructor and create objects

public class Text06 {
	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clz = (".");
		
		//Get a set of constructors		Constructor[] constructorArray1 = ();//public
		Constructor[] constructorArray2 = ();//public、private
		
		//Get the specified constructor		Constructor constructor1 = ();
		Constructor constructor2 = ();
		(constructor1);
		(constructor2);
		
		//Calling the private constructor, its full access limit must be set		(true);
		
		//Calling the constructor and creating the object		Object obj = ("Twenty Thousand Miles in Chang'an");
		(obj);
	}

}
  • getConstructors()Method returns a method that contains all public(public) Construct an array of methods. If there is no in the classpublicConstruct method, return an empty array.
  • getDeclaredConstructors()Methods return an array of all declared constructors (including private, protected, and default access level constructors).
  • getConstructor()Methods are used to obtain the parameterless constructor of the class (must bepublicof). If there is no parameterless construction method or notpublic, throwNoSuchMethodException
  • getDeclaredConstructor(Class<?>... parameterTypes)Methods are used to obtain the constructor of the specified parameter type. Here is theGet a parameter withStringConstructing method of parameters. This constructor can be at any access level (publicprivateprotected,default).
  • setAccessible(true)Used to bypass the Java access control mechanism so that private constructors can also be called. If not setAccessiblefortrue, then a private constructor will be thrown when callingIllegalAccessException
  • newInstance(Object... initargs)Methods use the specified constructor to create an object. Here is called withStringConstructing method of parameters and pass in"Twenty Thousand Miles in Chang'an"as a parameter.

8. Access and use member methods through reflection

public class Text08 {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		//Hardcoded method//		Document doc1 = new Document();
// ("Twenty thousand miles under the sea");//		(10025);
		
		//Reflection method		Class clz = (".");//Get type information		Object doc1 = ();//Create an object		
		//Get the method of specifying name and parameter type		Method setNameMethod = ("setName", );
		Method setFavCountMethod = ("setFavCount", );
		
		//Execution method		//("Twenty thousand miles under the sea");		(doc1, "Twenty Thousand Miles Under the Sea");
		//(10025);
		(doc1, 10025);
		
		(doc1);
		
	}

}
  • getMethod(String name, Class<?>... parameterTypes)Methods are used to obtain a classpublicmethod. The method name and parameter type must match to successfully obtain the method.
  • invoke(Object obj, Object... args)Methods are used to call specified instance methods.
  • (doc1, "Twenty thousand miles under the sea");Equivalent to("Twenty thousand miles under the sea");
  • (doc1, 10025);Equivalent to(10025);

9. Call static methods and process variable parameters through reflection

public class Text09_01 {
	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		//Hardcoded method		//Calling static method//		();
		
		String ret1 = ("The default initial capacity of HashMap is %d and the loading factor is %.2f", 16,0.75f);
		(ret1);
		
		
		//Reflection method//		Class clz = (".");
//		Method dosthMethod = ("dosth");
//		(null);
		
		Class clz = ;
		Method formatMethod = ("format", ,Object[].class);
		String ret2 = (null, "The default initial capacity of HashMap is %d and the loading factor is %.2f",new Object[] {16,0.75f}).toString();
		
		(ret2);
	}

}
  • This is the traditional way to call static methods directly. AssumptionDocumentThere is a class calleddosth()The static method can be called directly using the class name.
  • is a static method used to format strings, similar toprintfFormat rules
  • Get the Class object of the String class:useClass clz = ;
  • Get the Class object of the String class:useClass clz = ;
  • Calling static methods:useinvoke(null, "The default initial capacity of HashMap is %d, the loading factor is %.2f", new Object[] {16, 0.75f})Call static methods becauseformatIt is a static method, so the first parameter isnull
  • NoticeinvokeIn the method,Object[]The parameters must be passed in an array, so they are usednew Object[] {16, 0.75f}

10. Reflection performance issues

Although reflection is powerful, its performance is relatively low because it is a dynamic operation class at runtime. In addition, the reflection will also break

Bad packaging, be careful when using it.

11. The safety of reflection

Pay attention to security issues when using reflection, as it can bypass Java's access control mechanism. For example, private

fields or methods, so be careful when using reflection in development.

12. Common scenes of reflection

  • Framework Development: Such as dependency injection in Spring, ORM in Hibernate, etc.
  • Debugging Tools: Such as Java debuggers, analysis tools, etc.
  • Dynamic Agent: In Java, dynamic proxy relies on reflection.

Summarize

This is all about this article about the reflection mechanism in Java. For more related java reflection Reflection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • java
  • reflection

Related Articles

  • Understand kafka HA (high availability)

    This article mainly introduces the relevant knowledge of kafka HA (high availability). In this article, let’s talk about some strategies related to kafka HA. ​​Friends who are interested in kafka HA related knowledge will take a look.
    2021-11-11
  • Experience the entire process from stuttering to smooth

    This article mainly introduces the process of personal experience of Intellij Idea from lag to smoothness, which is of great reference value. I hope it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very encouraged.
    2023-09-09
  • Analysis of the process of implementing heartbeat mechanism in Java Netty

    This article mainly introduces the analysis of the heartbeat mechanism implementation of Java Netty. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.
    2020-03-03
  • Set up code formatting, comment templates and automatic formatting in Myeclipse

    This article mainly introduces setting up code formatting, annotation templates and automatic formatting methods in Myeclipse. Friends who need it can refer to it
    2014-10-10
  • Analysis of Spring Runtime Environment Environment

    This article mainly introduces the analysis of Spring operating environment Environment. The example code is introduced in very detailed, which has certain reference learning value for everyone's study or work. If you need it, please learn with the editor below.
    2023-08-08
  • Tips and example analysis of @Lazy annotation in Spring

    @Lazy annotation is used in the Spring framework to delay the initialization of beans and optimize application startup performance. It is not only suitable for @Bean and @Component, but also for injection points. By delaying the initialization of beans until the first use, unnecessary resource consumption can be reduced. This article introduces the usage skills and instance analysis of @Lazy annotation in Spring. Interested friends can take a look.
    2025-03-03
  • Java uses characters to draw a SpongeBob SquarePants

    This article mainly introduces in detail to Java using characters to draw a SpongeBob SquarePants. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2022-01-01
  • Java implements a method to read a specified file from a jar package

    This article mainly introduces Java to read specified files from jar packages, involving Java's reading and searching of jar files. Friends who need it can refer to it
    2017-08-08
  • Hadoop source code analysis three startup and script analysis

    This article is the third article in Hadoop source code analysis series, which mainly introduces Hadoop startup and script analysis. This series of articles will continue to be updated in the future. Friends in need can refer to it.
    2021-09-09
  • Understanding the core of JAVA: Uncovering the Mysteries of Reflection Mechanism

    Welcome to the JAVA Reflection Mechanism Guide! Want to know how to implement flexible programming skills in JAVA? This guide will take you to uncover the mystery of JAVA reflection mechanism and make your programming world more exciting! Come and explore with me!
    2024-02-02

Latest Comments