Java’s reflection mechanism?
Java reflection mechanism is a very powerful feature in many large projects such as Spring, Mybatis can see the reflection of the body. Through the reflection mechanism we can get the type of object information during the runtime, using this feature we can realize the factory model and proxy patterns and other design patterns, but also to solve the Java generic erasure and other vexing problems. The following java course from the perspective of practical applications to apply the reflection mechanism of Java.
p.s:This article requires readers to have a certain degree of understanding of the reflection mechanism of the API, if you have not been exposed to before, it is recommended to read the official documentation of QuickStart.
Before the application of the reflection mechanism, let’s first take a look at how to get an object corresponding to the reflection of the classClass, in the Java we have three ways to get the reflection class of an object.
Through the getClass method
In Java, every Object has a getClass method, and through the getClass method we can get the reflection class corresponding to this object:
Through the forName method
We can also call the Class class’ static method forName:
Or we can just use .class:
Getting type information
At the beginning of this article we mentioned that one of the great things about reflection is that it allows us to get type information about an object during runtime, so let’s look at that specifically through an example.
First we create a new interface A under the package typeinfo.interfacea:
Next we create a new interface A under the package typeinfo. packageaccess package, we create a new interface C, which inherits from interface A. We also create a couple of additional methods for testing, note that the following methods all have different permissions.
What is the principle of reflection inside Java?
Java will generate a class file after compilation, reflection through the bytecode file to find the methods and attributes, etc. in its class.
Through reflection, java can dynamically load unknown external configuration objects, temporarily generating bytecode to load and use, so that the code is more flexible, greatly improving the scalability of the application.
In fact, the blog will have a more detailed explanation.