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

The concept and Mechanism of Java reflection

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "the concept and mechanism of Java reflection". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the concept and mechanism of Java reflection".

1. What is a reflex?

What is a reflex? This is what the official document says:

Reflection is commonly used by programs which require the ability to examine ormodify the runtime behavior of applications running in the Java virtual machine.

This is a relatively advanced feature and should be used only by developers whohave a strong grasp of the fundamentals of the language.

With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible

Translate:

Reflection technology is often used to detect and change the behavior of applications in Java virtual machines. It is a relatively advanced technology, and its application is usually based on the developer's strong understanding of the Java language features. It is worth noting that reflection is a powerful technical feature that allows applications to perform purposes that are beyond the reach of conventional means.

Personal understanding: reflection is a very powerful x technology, the condition for using reflection is that the programmer is a great ape and understands the characteristics of java very well. The great thing about the reflex is that he can perform some unconventional operations.

Take a chestnut to illustrate:

After thinking about it for a moment, I think it is explained by cooking chestnuts. I don't know if it is accurate (^, ^). Usually we cook rice with an electric cooker at home. The steps of cooking are generally as follows: Amoy rice-- > dry the bottom of the pot-- > put the pot in the cooker-- > close the lid, turn on the electricity, work on the cooker-- > the rice is cooked and ready to eat, but now there is a need. I want to add an egg in the process of cooking. How can I solve it? Should I turn on the rice cooker that is cooking with electricity and put the eggs in it? (demand from foodie ^ _ ^) in fact, the reflection is equivalent to the process of adding eggs. So the reflex is very strong, he does not follow the conventional routine of playing cards, in the process of running the program to do some small moves, in order to achieve the purpose of "foodie". Add: "Amoy rice-- > dry the bottom of the pot-- > put the pot in the rice cooker-- >" this process can be seen as a coding compilation process, "--> close the lid, power on, the rice cooker work" can be seen as the process of running the program, "--> the rice is cooked." you can eat it "can be seen as the end of the program.

Reflection Mechanism in 2.java

2.1 Common classes in reflection

When you understand the reflection mechanism, first familiarize yourself with several classes:

1) Class class

The Class class instance represents the classes and interfaces in the running Java application. Class is an abstraction of ordinary classes, interfaces, enumerated classes, arrays, and so on, that is, their type is Class, and they are instances of Class.

Since Class represents classes and interfaces, we can get information about the corresponding classes or interfaces through his instance (bytecode file), such as comments, modifiers, types, class names, properties, methods, constructors, direct parents and subclasses, etc., and instances that can be created, but only by calling the no-parameter constructor.

What don't you understand? Take chestnut, for example, we all know that living things can be divided into animals, plants, microbes and viruses, while animals have humans, cats, puppies and so on, as well as plants, microbes and viruses. Similarly, we can compare that biology is Class, animals are ordinary classes, plants are interfaces, microorganisms are enumerated classes, viruses are arrays (enumerations and arrays are special classes), and people, cats and puppies are familiar objects, as shown in the figure.

You can see that ordinary classes, interfaces, enumerations, and arrays can all be treated as objects of Class.

2) Field class

Field represents the properties of a class, which contain modifiers, types, attribute names, and values. So you can get the modifier, type, and name of the property through the instance of Field, and you can modify the value of the property.

3) Method class

Method represents the member methods of a class, including annotations, modifiers, return types, method names, parameters, and so on. So you can get the information about the method through the instance of Method, such as comments, modifiers, return type, method name, and you can call the represented method.

4) Constructor class

Constructor represents the constructor, and you can get information about the constructor, such as modifiers, through an instance of Constructor, and you can use it to create an instance of the class it belongs to.

5) Modifier class

Modifier represents a modifier, which can be used to obtain information about the modifier, such as what kind of modifier, etc.

6) Annotation

Annotation representative comments

The above classes are located in java.lang

2.2 methods to get Class objects

After knowing what reflection is, do you also want to experience the coquettish operation of reflection?

If you want to show the operation, you must first get the Class object, because the Class object represents a variety of classes, and only with it can you get all kinds of information about the class. The acquisition method is as follows:

1) through object.getClass ()

Public static void main (String [] args) {Car car = new Car (); Class clazz = car.getClass ();}

Note: this method is not applicable to int, float and other types.

2) pass (type name) .class, wrapper class .Type

Public static void main (String [] args) {Class clazz = Car.class; Class cls1 = int.class; Class cls2 = String.class; Class cls3=Iteger.Type}

3) through Class.forClass (the fully qualified name of the String class)

1 try {2 Class clz = Class.forName ("com.frank.test.Car"); 3} catch (ClassNotFoundException e) {4 e.printStackTrace (); 5}

Which method is used to obtain it depends on the actual situation.

2.3 get class information

Once you have the Class object, you can get the class members (methods + properties), annotations, class modifiers, and so on. As mentioned above, methods in java are represented by Method classes, attributes are represented by Field classes, annotations are represented by Annotation classes, and modifiers are represented by Modifier classes. There are corresponding methods in the Class class to get them. As follows:

2.3.1 get the object of the property Field

/ / get all the attributes, but not the property public Field [] getDeclaredFields () throws SecurityException / / inherited from the parent class to get all of its own public properties, including those inherited from the parent class. Public Field [] getFields () throws SecurityException// gets the specified attribute declared in this class. The parameter is the name of the attribute public Field getDeclaredField (String name) / / gets the specified public attribute, including the name of the parent class, and the parameter is the name of the attribute public Field getField (String name).

2.3.2 get method Method object

/ / get the method specified by this class declaration. The first parameter is the name of the method, followed by the class of the method parameter type. / / for example, get the setName (String name) method, getDeclareMethod ("setName", String.Class) public Method getDeclaredMethod (String name, Class)

< ?>

... ParameterTypes) / / get the public method, including the public Method getMethod (String name, Class) of the parent class

< ?>

... ParameterTypes) / / get all methods declared in this class public Method [] getDeclaredMethods () / / get all public methods, including public Method [] getMethods () of the parent class

2.3.3 get the constructor Constructor object

/ / get the constructor public ConstructorgetDeclaredConstructor (Class) specified in this class

< ?>

... ParameterTypes) / / get the specified public constructor public ConstructorgetConstructor (Class)

< ?>

... ParameterTypes) / / get all the constructors public Constructor in this class

< ?>

[] getDeclaredConstructors () throws SecurityException / / get all the public constructors public Constructor in this class

< ?>

[] getConstructors ()

The acquisition of a constructor is roughly the same as that of a common method.

-

The above methods are all in the Class class, so don't be silly to know (don't ask me how I know > _ >), and then call it through the Class object.

Here just enumerate the commonly used class information acquisition methods, other information acquisition methods, see API documents, such as notes, class Class object (the forehead seems to be a little around. ), etc.

2.4 get class member information

The above only gets the objects of the class represented by the members of the class, and we also use them or get information about the members (names, modifiers, etc.). Because you have an object that represents a member, you can use the object to call the instance method.

2.4.1 Field class

The methods of the Field class can be divided into two types, one is to get the information about the property, and the other is to set the value of the property.

The first kind:

/ / returns the name of the field represented by the Field object String getName () / / returns a class object that identifies the declaration type of the field represented by the Field object. Class

< ?>

GetType () / / returns the Java language modifier of the field represented by the Field object as an integer. Taking an integer as an argument to the constructor of Modifier, you can get the object of the modifier class represented by the integer int getModifiers ()-/ / get the value of a static or instance field of type int Or the value of another primitive type that is converted to the type int by extension. Int getInt (Object obj) / / gets the value of a static or instance field of type long, or another base type value that can be converted to type long by expanding the conversion. Long getLong (Object obj). Omit a bunch of get** (Object obj) methods here, and just get what the basic type is. 14 if the property is a reference type, call the following method / / to return the Field of the field represented, on the specified object. 16 Object get (Object obj)

The second kind:

/ / set on the object specified as the value of a field double. Void setDouble (Object obj, double d) / / is set on the object specified as the value float of a field. Void setFloat (Object obj, float f) / / is set on the object specified as the value int of a field. Void setInt (Object obj, int I). Omit a bunch of set** () methods here, and just set what the property is. If the property is a reference type, call the following method / / to set the field represented by this Field object on the specified object parameter to the specified new value. Void set (Object obj, Object value)

Note: if you do not have access, you cannot set property values by default, so what do you do? Is it impossible to show the operation? However, as mentioned earlier, the reflection is very strong, so we can do some unconventional operations.

At this point, we can call the setAccessible (true) method of the Class object!

Do you think the reflex can be strong?

2.4.2 Method class

The method of the Method class is mainly to obtain the information of the method.

Part of the method:

1 int getModifiers () / / returns the Java language modifiers of the executable represented by the object. 2 String getName () / / returns the name of the method represented by this method object as String. 3 Annotation [] [] getParameterAnnotations () / / returns an array of Annotations representing the Executable of the declaration order of the formal parameters of the Executable represented by the object. 4 int getParameterCount () / / returns the number of formal parameters (whether explicitly or implicitly declared) of the executable file represented by this object. 5 Class

< ?>

[] getParameterTypes () / / returns an array of class objects that represent, in declarative order, the formal parameter types of the executable file represented by that object.

2.4.3 Constructor class

The method of the Constructor class is mainly to obtain the information of the constructor and create the object.

Get method information:

1 int getModifiers () / / returns the Java language modifiers of the executable represented by the object. 2 String getName () / / returns the name of this constructor as a string. 3 Annotation [] [] getParameterAnnotations () / returns the array parameters represented by the array Annotation to annotate s, declaring the order of the Executable of the object representation. 4 int getParameterCount () / / returns the number of formal parameters (whether explicitly or implicitly declared) of the executable file represented by this object. 5 Class

< ?>

[] getParameterTypes () / / returns an array of class objects that represent, in declarative order, the formal parameter types of the executable file represented by that object.

Put aside the method of creating an object and put it in the back.

2.5 reflection creates objects and invokes methods

2.5.1 create objects of normal classes

There are two ways to create objects of a normal class

The first: the method of calling the Class object

4 / / first get Class object 5 Class clazz=Class.forClass ("test.Student"); 6 / / create object 7 Student stu= (Student) clazz.newInstance (); Note: this method can only create objects of classes with no parameter constructor

The second: through the newInstance () method of Constructor

/ / first create the Class object Class clazz=Class.forClass ("test.Student"); / / get the constructor Constructor constructor=clazz.getConstructor (String.class, int.class) you want to call; / / call Constructor's newInstance () method Student stu= (Student) constructor.newInstance ("King", 20)

2.5.2 create an array

An array is essentially a Class, and there is a method in Class to identify whether it is an array.

Reflection creates an array through the Array.newInstance (T.class, dimension) method.

The first parameter specifies the element type in the array, followed by a variable parameter, which represents the array length limit of the corresponding dimension.

For example, I'm going to create an array of int [2] [3].

1 Int [] [] a=Array.newInstance (Integer.TYPE, 2,3)

2.5.3 calling method

Using the above method, there are Class objects, method Method objects, and instances. Now everything is ready, except Dongfeng.

So how do we call the method? There is a method Object invoke (Object obj, Object...) in the Method class Args), object is the instance object, and args is the parameter of the calling method

Have a chestnut:

Class

< ?>

C = Class.forName ("com.kal01.reflect05.Person"); / / get the Class object Person p1 = (Person) c.newInstance (); / / get the instance Method m3 = c.getDeclaredMethod ("test"); / / get the method m3.setAccessible (true); / / when you don't have access, you can m3.invoke (p1); / / call the method m3.setAccessible (false); / / modify the access permission, remember to modify it back.

2.6 static loading and dynamic loading

Seeing whether there is a question here, the method of the reflection calling class seems to be no different from what we normally call, except for complexity. Why do you have to be so fancy?

So let's talk briefly about static loading and dynamic loading here.

Thinking back to the chestnut that was cooked before, the example of static loading is somewhat similar to that of dynamic loading.

Static loading: when we use a class in a program, static loading requires that the class to be used must exist at the time of compilation, otherwise the compiler reports an error and cannot run the program. This error often occurs when you forget to guide the package while coding.

Dynamic loading: use reflection to load the class (that is, get the Class object), do not require us to exist at compile time if the class is used, when the program is running, look for the class (you can look for it from the jar package, network, etc.), and then load the class into the method area. If you do not find this class, you will throw a ClassNotFoundException exception.

There is a picture and the truth:

Thank you for your reading, the above is the content of "the concept and mechanism of Java reflection". After the study of this article, I believe you have a deeper understanding of the concept and mechanism of Java reflection, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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