Java reflection easy tutorial

About java reflection, we need to understand the following questions:

What is reflection? What's the use of reflection? How to use reflection?

Let's explain them one by one:

1、 What is reflection?

Reflection means "reflection, image and reflection". In Java, it means that we can load, discover and use classes completely unknown during compilation at runtime. In other words, a java program can load a class whose name is known only at runtime, learn its complete structure (but excluding the methods definition), and generate its object entity, set its fields, or invoke its methods.

Java reflection mechanism is to know all the properties and methods of any class in the running state; Any method of any object can be called; This function of dynamically obtaining information and dynamically calling methods of objects is called java reflection mechanism.

1. Introspection vs. reflection

Reflection is often confused with introspection. To distinguish them, let's take a look at their detailed definitions:

Introspection:

Introspectionistheabilityofaprogramtoexaminethetypeorpropertiesof

anobjectatruntime.

Reflection:

Reflectionistheabilityofaprogramtoexamineandmodifythestructure

andbehaviorofanobjectatruntime.

From the above definition, we can see that introspection is a subset of reflection. Some languages support introspection, but do not support reflection, such as C + +.

2. Introspective example vs. reflective example

Introspection example: the instanceof operator is used to determine whether an object belongs to a specific class.

Reflection instance: class The forname () method returns an object of a specific class / interface. Of course, the parameter needs to be specified as a specific class name.

2、 Why reflection?

Java reflection is particularly important in framework development. In some cases, the class we want to use will be determined at runtime. At this time, we can't use it at compile time. Therefore, we can only use the class that exists at runtime in the form of reflection (this class conforms to a specific specification, such as JDBC). This is a scenario where reflection is used more.

During compilation, we do not know the internal information of the class. We must get the runtime to obtain the specific information of the class. For example, the ORM framework can obtain each attribute in the class at runtime, and then obtain its attribute name and value in the form of reflection and store it in the database.

Functions provided by reflection mechanism:

Judge the class of any object at run time; Construct the object of any class at runtime; Judge the member variables and methods of any class at run time; Call the method of any object at run time. You can even call private methods through reflection; Modify the access rights of constructors, variables and methods at run time.

decoupling

If we have two programmers, one programmer needs to use the class written by the second programmer when writing the program, but the second programmer does not complete the class he wrote. Can the first programmer's code be compiled? This cannot be compiled. Using the java reflection mechanism, the first programmer can compile his own code without getting the class written by the second programmer

When calling and instantiating a class, configure the corresponding class name in the configuration file, read the class name in the program, and then load and instantiate it in the program through reflection technology, such as common database driver classes. In order to achieve independence from specific database driver classes, Put the database driver class name into the configuration file (commonly used are XML file, properties file and text file), and then load the driver in the program to realize the decoupling of the database, that is, as long as the configuration file is modified, the database type can be easily changed.

For example, spring uses the following bean configuration:

When spring is processing, it will use class Forname (string), and the parameter "com. XXX. Foo" is used to instantiate this class. At the same time, use reflection settings to set specific values.

This mechanism is also used for web applications of servlets:

3、 Reflection API

Java reflection related classes

Not many classes are required for java reflection, mainly Java Lang.class class java The field, constructor, method and array classes in lang.reflect package are described as follows:

Class: an instance of class represents classes and interfaces in a running Java application. Field class: provides information about the properties of a class or interface and dynamic access permissions to it. The reflected field may be a class attribute or instance attribute. Simply understand it as a class that encapsulates the attributes of the reflected class. Constructor class: provides information about a single constructor of a class and access rights to it. This class is different from the field class. The field class encapsulates the properties of the reflection class, while the constructor class encapsulates the construction method of the reflection class. Method class: provides information about a single method on a class or interface. The reflected methods may be class methods or instance methods (including abstract methods). This class is not difficult to understand. It is a class used to encapsulate reflective class methods. Array class: provides static methods for dynamically creating arrays and accessing arrays. All methods in this class are static methods.

Class

Class is a part of a program. Each class has a class object. In other words, whenever a new class is written and compiled, a class object is generated.

Class has no public constructor. Class objects are automatically constructed by the Java virtual machine when loading classes and by calling the defineclass method in the class loader. Therefore, a class object cannot be declared explicitly

Class is the origin of reflection. To manipulate; The properties and methods of a class must start from obtaining classobject.

Class method

Getname(): get the full name of the class. Getfields(): get the public type attribute of the class. Getdeclaraedfields(): get all the properties of the class. Getmethods (): get the public type method of the class. Getdeclaraedmethods(): get all the methods of the class. Getmethod (stringname, class [] parametertypes): get the specific method of the class. The name parameter specifies the name of the method, and the cparametertypes parameter specifies the parameter type of the method. Getconstructors (): get the constructor of the public type of the class. Getconstructor (class [] parametertypes): get the specific constructor of the class. The parametertypes parameter specifies the parameter type of the constructor. Newinstance(): create an object of the class through the class's nonparametric constructor.

Constructor

Get the construction method of the class

Constructor getconstructor (class [] params) C obtains public constructors using special parameter types constructor [] getconstructors() C obtains all public constructors of the class constructor getdeclaraedconstructor (class [] params) C obtains constructors using specific parameter types (independent of access level) constructor [] getdeclaraedconstructors() C obtains all constructors of the class (independent of access level)

Field

Get class definition variable

Fieldgetfield (stringname) C gets the named public fieldfield [] getfields() C gets all the public fields of the class fieldgetdeclaraedfield (stringname) C gets the named fields of the class declaration fieldfield [] getdeclaraedfields() C gets all the fields of the class declaration

Method

Get class definition method

Methodgetmethod (stringname, class [] parameters) C uses specific parameter types to obtain named public methods. Method [] getmethods() C obtains all public methods of the class. Methodgetdeclaredmethod (stringname, class [] parameters) C uses close-up parameter types to obtain named methods declared by the class. Method [] getdeclaredmethods() C obtains all methods declared by the class

4、 How does reflection work?

In the previous chapter, we explained the java reflection API. In this chapter, we will use some code examples to show how to use these reflection APIs.

Example1: get class name from object

Output:

Example 2: call method of unknown object

Imagine that we don't know the type of an object, but through reflection, we can use the object and find out whether the object has a method named print and call it, as shown below:

Output:

Example 3: create an object from a class instance

Example 4: get constructor and create instance

Output:

In addition, you can use the class instance and get the implemented interface, parent class, declared method, etc.

Example 5: modify array size through reflection

Output:

5、 Summary

This article only explains the small content of java reflection. If you are interested in learning more information, you can find information from the network.

The above is the whole content of this simple tutorial on java reflection. I hope it will be helpful to you. Interested friends can continue to refer to this site: what you need to know about java reflection mechanism, Java RTTI and reflection mechanism code analysis. You can leave a message at any time if you have any questions. Xiaobian will reply to you in time. Thank you for your support!

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
分享
二维码
< <上一篇
下一篇>>