Detailed explanation of the reflection mechanism in java
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 obtainClass
Object.Class
Objects 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 into
Document
Object of class. During parsing, the data in the JSON string will be automatically mapped toDocument
in the corresponding field of the class.
5. Class type object usage scenario 2
passClass
The 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 oneField
Array, containing all fields declared by the class (including private fields). -
()
Return oneMethod
Array, containing all methods declared by the class (including private methods).
6. Create an object through reflection
Method 1: ByClass
Objects 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 isClass
An 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 it
Constructor
Object to create instances. - pass
getDeclaredConstructor()
Method ObtainDocument
The parameterless constructor of the class, and then callnewInstance()
Method creates an instance. -
Notice: If there is no parameterless constructor in the class, call
getDeclaredConstructor()
Will be thrownNoSuchMethodException
。 - pass
getDeclaredConstructor()
Get with oneString
Constructing method of parameters and pass in"Fifteenth Day in Two Capitals"
Create an object as a parameter. - pass
getDeclaredConstructor()
Get with oneint
Constructing method of parameters and pass in34
Create 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 classpublic
Construct 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 bepublic
of). 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 with
String
Constructing method of parameters. This constructor can be at any access level (public
、private
、protected
,default). -
setAccessible(true)
Used to bypass the Java access control mechanism so that private constructors can also be called. If not setAccessible
fortrue
, then a private constructor will be thrown when callingIllegalAccessException
。 -
newInstance(Object... initargs)
Methods use the specified constructor to create an object. Here is called withString
Constructing 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 classpublic
method. 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. Assumption
Document
There is a class calleddosth()
The static method can be called directly using the class name. -
is a static method used to format strings, similar to
printf
Format rules -
Get the Class object of the String class:use
Class clz = ;
。 -
Get the Class object of the String class:use
Class clz = ;
。 -
Calling static methods:use
invoke(null, "The default initial capacity of HashMap is %d, the loading factor is %.2f", new Object[] {16, 0.75f})
Call static methods becauseformat
It is a static method, so the first parameter isnull
。 -
Notice
invoke
In 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!
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-11Experience 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-09Analysis 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-03Set 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 it2014-10-10Analysis 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-08Tips 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-03Java 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-01Java 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 it2017-08-08Hadoop 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-09Understanding 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