Java reflection mechanism example tutorial

This paper describes the reflection mechanism of Java in detail in the form of examples, which is an important skill in Java programming. Share with you for your reference. The specific analysis is as follows:

Firstly, reflection is one of the features of Java programming language. It allows running Java programs to check themselves, or "self audit", and can directly operate the internal properties of the program. For example, you can use it to get the names of the members in the Java class and display them. This capability of Java may not be used much in practical applications, but it does not exist in other programming languages. For example, in Pascal, C, or C + +, there is no way to obtain information about function definitions in a program.

JavaBean is one of the practical applications of reflection. It allows some tools to visually operate software components. These tools dynamically load and obtain the properties of Java components (classes) through reflection.

1. A simple example

Consider the following simple example to see how reflection works.

Its result output is:

This lists Java util. The name of each method of the stack class and their qualifiers and return types.

This program uses class ForName loads the specified class and then calls getDeclaredMethods to get the list of methods defined in this class. java. lang.reflect. Methods is a class used to describe a single method in a class.

2. Start using reflection

Classes for reflection, such as method, can be found in Java Found in lang.relfect package. There are three steps to follow when using these classes: the first step is to get the Java. Java. Java of the class you want to operate on Lang. class object. In a running Java program, use Java Lang. class class to describe classes, interfaces, etc.

The following is one of the methods to obtain a class object:

This statement gets a class object of string class. There is another method, such as the following statement:

Class c = int.class; Or class C = integer TYPE;

They can obtain class information of basic types. The latter method accesses the predefined type field in the encapsulated class of the basic type (such as integer).

The second step is to call a method such as getdeclaraedmethods to get a list of all the methods defined in the class.

Once this information is obtained, you can proceed to the third step - use the reflection API to manipulate this information, as shown in the following code:

It will print out the prototype of the first method defined in the string as text.

In the following example, these three steps will provide an example of using reflection to deal with a special application.

Simulate instanceof operator

After getting the class information, the next step is usually to solve some basic problems about the class object. For example, class The isinstance method can be used to simulate the instanceof operator:

In this example, create a class object of class s, and then check whether some objects are instances of S. Integer (37) is not, but new s() is.

3. Find out the method of class

Finding out what methods are defined in a class is a very valuable and basic reflection usage. The following code implements this usage:

This program first obtains the description of method1 class, and then calls getDeclaredMethods to get a series of Method objects, which respectively describe each method defined in the class, including public method, protected method, package method and private method. If you use getmethods instead of getdeclaredmethods in your program, you can also get the information of each inherited method.

After obtaining the method object list, it is not difficult to display the parameter types, exception types and return value types of these methods. Whether these types are basic types or class types can be given in order by the objects describing the class.

The output results are as follows:

4. Get constructor information

The usage of the acquisition class constructor is similar to that of the above acquisition methods, such as:

In this example, the information about the return type is not available because the constructor has no return type.

The result of this program is:

5. Get the field (domain) of the class

It is also possible to find out which data fields are defined in a class. The following code is doing this:

This example is very similar to the previous one. In the example, a new thing modifier is used. It is also a reflection class, which is used to describe the modifiers of field members, such as "private int". These modifiers themselves are described by integers and use modifier ToString to return string descriptions in "official" order (e.g. "static" before "final"). The output of this program is:

In the case of obtaining methods, when obtaining fields, you can only obtain the field information declared in the current class (getdeclaraedfields), or you can also obtain the fields defined in the parent class (getfields).

6. Execute the method according to the name of the method

Text here, all the examples are related to how to obtain class information. We can also use reflection to do other things, such as executing a method with a specified name. The following example demonstrates this:

If a program only knows that it needs to execute a method when it is executing somewhere, and the name of this method is specified during the running process of the program (for example, this will be done in the JavaBean development environment), the above program demonstrates how to do it.

In the above example, getmethod is used to find a method named add with two integer parameters. After finding the method and creating the corresponding method object, execute it in the correct object instance. When executing this method, you need to provide a parameter list, which in the above example is two integer objects that wrap integers 37 and 47 respectively. The return of the execution method is also an integer object, which encapsulates the return value 84.

7. Create a new object

For constructors, you can't do it like executing methods, because executing a constructor means creating a new object (to be exact, the process of creating an object includes allocating memory and constructing an object). Therefore, the most similar examples to the above example are as follows:

Find the corresponding constructor according to the specified parameter type and execute it to create a new object instance. Using this method, you can dynamically create objects when the program is running, rather than creating objects when compiling, which is very valuable.

8. Change the value of the field (field)

Another use of reflection is to change the value of the object data field. Reflection can find the field of the object by name from the running program and change it. The following example can illustrate this:

In this example, the value of field D is changed to 12.34.

9. Using arrays

The last use of reflection introduced in this article is to create an array of operations. Array is a special class type in the Java language. An array reference can be assigned to an object reference. Look at the following example to see how arrays work:

In the example, 10 string arrays of unit length are created, and the value is assigned to the string at the fifth position. Finally, the string is obtained from the array and printed.

The following code provides a more complex example:

In the example, an integer array of 5 x 10 x 15 is created, and the element at [3] [5] [10] is assigned a value of 37. Note that a multidimensional array is actually an array of arrays, for example, the first array After get, arrobj is a 10 x 15 array. Then get one of the elements, that is, an array with a length of 15, and use array Setint assigns a value to its 10th element.

Note that the type of array is dynamic when it is created, and its type is not known at compile time.

I believe this article has a certain reference value for everyone to learn java programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>