Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the reflection mechanism of java and its common application scenarios?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "java reflection mechanism and what are common application scenarios". In daily operation, I believe many people have doubts about java reflection mechanism and common application scenarios. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "java reflection mechanism and common application scenarios". Next, please follow the editor to study!

What is java reflection?

In the process of object-oriented programming in java, we usually need to know a Class class first, and then new the class name () to get the object of that class. In other words, we need to know which class we want to instantiate and which method to run when we write code (at compile time or before class loading), which is often referred to as static class loading.

But in some scenarios, we don't know the specific behavior of our code in advance. For example, we define a service task workflow, where each service task is a method of the corresponding class.

Which method of which class is executed by service task B is determined by the execution result of service task A.

Which method of which class is executed by service task C is determined by the execution results of service tasks An and B

And the user does not want the function of the service task to be written dead in the code, but wants to execute different programs according to different conditions through configuration, and the conditions themselves are also changing.

Faced with this situation, we can not use the code new class name () to implement, because you do not know exactly how to configure, this second he wants the service task A to execute the x method of the Xxxx class, and the next second he may want to execute the y method of the Yyyy class. Of course, you can also say to mention the demand, the user changes the demand once, I change the code once. This approach can also be required, but it is painful for both users and programmers, so is there a way to dynamically change the calling behavior of the program at run time? This is the "java reflection mechanism" I want to introduce to you.

So what can java's reflection mechanism do? It is roughly as follows:

Dynamically according to the package name at run time of the program. Class name instantiates class object

Dynamically obtain the information of the class object during the run time of the program, including the object's cost variables and methods

Dynamically use the object's member variable properties at run time of the program

Dynamically call the method of the object at run time of the program (private methods can also be called)

II. Hello World

Enter the door first, the boss can skip this paragraph. We define a class called Student

Package com.zimug.java.reflection;public class Student {public String nickName; private Integer age; / / this is private public void dinner () {System.out.println ("dinner!") ;} private void sleep (int minutes) {/ / private modifier System.out.println ("sleep" + minutes + "minutes");}}

If you don't use reflection, I'm sure friends who have studied java will definitely call the dinner method.

Student student = new Student (); student.dinner ()

How do we call it if it's a reflection?

/ / get Student class information Class cls = Class.forName ("com.zimug.java.reflection.Student"); / / object instantiation Object obj = cls.getDeclaredConstructor (). NewInstance (); / / get and execute method Method dinnerMethod = cls.getDeclaredMethod ("dinner") according to the method name; dinnerMethod.invoke (obj); / / print: dinner!

From the above code, we can see that the com.zimug.java.reflection.Student class name and the dinner method name are strings. Since it is a string, we can execute this program through a configuration file, or a database, or some other flexible configuration method. This is the most basic use of reflection.

Third, the relationship between class loading and reflection

The class loading mechanism of java is quite complicated, and in order not to confuse the key points, we will only introduce some of the contents that have something to do with "reflection".

When java performs compilation, the java file is compiled into a bytecode class file, and the class loader loads the class file into memory during the class loading phase, and instantiates an java.lang.Class object. For example, for the Student class, there will be the following actions during the load phase:

Instantiate a Class object in memory (method area or code area). Note that the Class object is not a Student object

A Class class (bytecode file) corresponds to a Class object and has only one

The Class object holds the basic information of the Student class, such as how many fields (Filed) does the Student class have? How many construction methods (Constructor) are there? How many methods are there (Method)? What are the comments (Annotation)? Wait for information

With the above basic information object (java.lang.Class object) about the Student class, the object of the Student class can be instantiated at run time based on this information.

At runtime you can directly new a Student object

You can also use the reflection method to construct a Student object

But no matter how many Student objects you new, no matter how many Student objects you reflect and build, there is only one java.lang.Class object that holds information about the Student class. The following code can prove it.

Class cls = Class.forName ("com.zimug.java.reflection.Student"); Class cls2 = new Student (). GetClass (); System.out.println (cls = = cls2); / / compare the address of the Class object, the output is true 4, the java class reflected by the operation

With the above basic information, we can learn more about the classes and methods related to reflection classes:

Java.lang.Class: represents a class

Java.lang.reflect.Constructor: represents the constructor of a class

Java.lang.reflect.Method: a common method that represents a class

Java.lang.reflect.Field: a member variable that represents a class

Java.lang.reflect.Modifier: modifiers, method modifiers, member variable modifiers.

Java.lang.annotation.Annotation: you can annotate classes, member variables, constructors, and common methods.

4.1. Three methods of getting Class object

The Class.forName () method gets the Class object

The / * Class.forName method gets the Class object, which is also the most commonly used method in reflection, because passing parameters in a string enhances the flexibility of the configuration implementation * / Class cls = Class.forName ("com.zimug.java.reflection.Student")

Class name .class gets the Class object

/ * `Class name .class` gets the Class object * / Class clz = User.class

Class object. GetClass () method to get Class object

/ * `class object. GetClass ()` gets the Class object * / User user = new User (); Class clazz = user.getClass ()

Although there are three ways to get the Class object of a class, only the first can be called "reflection".

4.2. Get the basic information of the Class class object Class cls = Class.forName ("com.zimug.java.reflection.Student"); / / get the package name of the class + class name System.out.println (cls.getName ()); / / com.zimug.java.reflection.Student// get the parent class of the class Class cls = Class.forName ("com.zimug.java.reflection.Student"); / / is this type a comment? Is the type System.out.println (cls.isAnnotation ()) / / false// an enumeration? Is the type System.out.println (cls.isEnum ()) / / false// the underlying data type? System.out.println (cls.isPrimitive ()); / / false

The Class class object information contains almost all the information you want to know about this type definition, so there are no more methods to enumerate. You can also use the following methods

Get which interfaces the class represented by the Class class object implements: getInterfaces ()

Get which annotations are used by the class represented by the Class class object: getAnnotations ()

4.3. Get the member variables of the Class object

Understand the following code in conjunction with the definition of the Student class above

Class cls = Class.forName ("com.zimug.java.reflection.Student"); Field [] fields = cls.getFields (); for (Field field: fields) {System.out.println (field.getName ()); / / nickName} fields = cls.getDeclaredFields (); for (Field field: fields) {System.out.println (field.getName ()); / / nickName wrap age}

The getFields () method gets the non-private member variables of the class, the array, containing the member variables inherited from the parent class

The getDeclaredFields method gets all member variables, arrays, but does not contain member variables inherited from the parent class

4.4. Get the method of Class object

GetMethods (): gets all the non-private methods, arrays, and methods inherited from the parent class of the class represented by the Class object

GetDeclaredMethods (): gets all the methods, arrays, defined by the class represented by the Class object, but does not contain methods inherited from the parent class

GetMethod (methodName): a non-private method that gets the specified method name of the class represented by the Class object

GetDeclaredMethod (methodName): a method that gets the specified method name of the class represented by the Class object

Class cls = Class.forName ("com.zimug.java.reflection.Student"); Method [] methods = cls.getMethods (); System.out.println ("non-private method of Student object"); for (Method m: methods) {System.out.print (m.getName () + ",");} System.out.println ("end"); Method [] allMethods = cls.getDeclaredMethods () System.out.println ("all methods of Student object"); for (Method m: allMethods) {System.out.print (m.getName () + ",");} System.out.println ("end"); Method dinnerMethod = cls.getMethod ("dinner"); System.out.println ("number of parameters of dinner method" + dinnerMethod.getParameterCount ()) Method sleepMethod = cls.getDeclaredMethod ("sleep", int.class); System.out.println ("number of parameters of sleep method" + sleepMethod.getParameterCount ()); System.out.println ("Array of parameter objects of sleep method" + Arrays.toString (sleepMethod.getParameters (); System.out.println ("Parameter return value type of sleep method" + sleepMethod.getReturnType ())

The execution result of the above code is as follows:

Non-private methods of Student object

Dinner,wait,wait,wait,equals,toString,hashCode,getClass,notify,notifyAll, end

All methods of the Student object

Dinner,sleep, end

The number of parameters of dinner method is 0

The number of parameters of sleep method is 1

Parameter object array of the sleep method [int arg0]

The parameter return value type void of the sleep method

You can see that the method obtained by getMethods contains the method defined in the Object parent class, but does not include the private method sleep defined in this class. In addition, we can also obtain the parameters and return value information of the method:

Get the properties related to the parameter:

Get the number of method parameters: getParameterCount ()

Get the method parameter array object: getParameters (), and the return value is the java.lang.reflect.Parameter array

Get the properties related to the return value

Get the data type of the return value of the method: getReturnType ()

4.5. Method invocation

In fact, the method call has been demonstrated above, as follows: invoke calls the dinner method

Method dinnerMethod = cls.getDeclaredMethod ("dinner"); dinnerMethod.invoke (obj); / / print: dinner!

The dinner method has no parameters, so how can a method with parameters be called? Looking at the invoke method definition, the first parameter is the Method object, regardless of the subsequent Object... How many parameters args has can be passed in turn according to the definition of the method.

Public Object invoke (Object obj, Object... Args) 4. 6. Create the object of the class (instantiate the object) / / get the Student class information Class cls = Class.forName ("com.zimug.java.reflection.Student"); / / instantiate the object Student student = (Student) cls.getDeclaredConstructor (). NewInstance (); / / the following method is already Deprecated and is not recommended. But it's still the only way in older versions of JDK. / / Student student = (Student) cls.newInstance (); 5. Common scenes of reflection

Call the method of the class through the configuration information

Combined with annotations to realize special functions

Load jar packages or class on demand

5.1. Call the method of the class through the configuration information

Encapsulating the code in the hello world above, do you know whether the class name className and the method name methodName can call the method? As for whether you configure className and methodName to files, nacos or database, it's up to you to decide.

Public void invokeClassMethod (String className,String methodName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {/ / get class information Class cls = Class.forName (className); / / object instantiation Object obj = cls.getDeclaredConstructor (). NewInstance (); / / get and execute the method Method dinnerMethod = cls.getDeclaredMethod (methodName) based on the method name DinnerMethod.invoke (obj);} 5.2. Combined with annotations to realize special functions

If you have studied mybatis plus, you should have learned such an annotation TableName, which indicates which table in the database corresponding to the current entity class Student. As shown in the following question code, Student shows that this class corresponds to the t_student table.

@ TableName ("t_student") public class Student {public String nickName; private Integer age;}

Let's customize the TableName annotation.

@ Target (ElementType.TYPE) / / means that TableName can act on a class, interface, or enum Class, or interface@Retention (RetentionPolicy.RUNTIME) / / means that public @ interface TableName {String value () is loaded by JVM at runtime; / / when the @ TableName annotation is used: @ TableName ("t_student");}

With this annotation, we can scan the java file under a certain path. As for the scanning of class annotations, we don't have to develop it ourselves, we can introduce the following maven coordinates.

Org.reflections reflections 0.9.10

Take a look at the following code: first scan the package, get the class marked with TableName annotations from the package, and then print the annotated value information for the class

/ / package to be scanned String packageName = "com.zimug.java.reflection"; Reflections f = new Reflections (packageName); / / get the collection of scanned tag comments Set cls = classLoader.loadClass ("com.zimug.java.reflection.Student")

Does the dynamic loading of the class remind you of anything? Is it possible to modify the code without restarting the web container? Yes, that's the principle, because there is only one Class object for a class, so no matter how many times you reload, you use the last loaded class object (mentioned above).

VI. Advantages and disadvantages of reflection

Advantages: free, flexible to use, not restricted by the access rights of the class. The method call can be implemented according to the specified class name and method name, which is very suitable for the flexible configuration of the business. It is also widely used in framework development, especially in combination with annotations.

Disadvantages:

Because reflection is not restricted by the access rights of the class, its security is low, and most of the java security problems are caused by reflection.

Compared to normal object access calls, reflection has relatively low performance because of the instantiation of classes and methods.

The encapsulation of the java class is destroyed, the information hiding and boundaries of the class are destroyed.

At this point, the study of "what are the java reflection mechanisms and common application scenarios" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report