What you need to know about java reflection mechanism

As we all know, in order for Java programs to run, Java classes must be loaded by the Java virtual machine. Java classes cannot run normally if they are not loaded by the Java virtual machine. All the programs we run now know that the class you need has been loaded at compile time.

Java's reflection mechanism is not sure which class is loaded during compilation, but only when the program is running. Use classes that are not known at compile time. Such a feature is reflection.

Reflection mechanism is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically acquired information and the function of dynamically calling object methods are called the reflection mechanism of Java language.

This article will describe the knowledge of reflection from the following aspects:

Calss uses the reflection constructor of the reflection method to reflect the reflection of member variables

1、 What is a class

In the object-oriented world, everything is an object. Class is an object and class is Java Instance object of lang.class class. In addition, only the Java virtual machine can new the class. Any class is an instance object of class. This instance object can be expressed in three ways:

2、 Dynamic loading of class

Class. Forname (full name of the class); This method not only represents the type of class, but also represents the dynamically loaded class. The compile time loading class is static loading, and the run time loading class is dynamic loading.

3、 Get method information

The basic data type and void keyword are instances of class; You can use get ame(); Getsimplename() gets the name of the class.

Get all the methods of the class and print them out:

function:

4、 Get information about member variables

You can also get the member variable information of the class

function:

5、 Get constructor information

function:

6、 Operation of method reflection

Get a method: you need to get the name and parameters of the method to determine a method.

Reflection operation of method:

for instance:

function:

This article has explained the basic usage of java reflection, which can 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; Generate dynamic proxy.

The above is all about java reflection mechanism in this article. I hope it will be helpful to you.

For more relevant contents, please refer to: Java RTTI and reflection mechanism code analysis, in-depth understanding of java reflection mechanism, and detailed explanation of java reflection mechanism examples.

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