First, look at a few questions.
1. What is the difference between class and class?
2. Several ways to get the bytecode (class) of a class
An example illustrates:
Output Result:
3. Concept
I didn't want to talk about concepts because there were a lot of them online. And I don't think I can tell you anything new, but in order to make it easier to understand, let's say:
Reflection simplicity appears to be the use of special classes to represent some of the components of a universal class (constructor, member property, member method). Why? Because everything
It is the object of the Constructor,field,method, which leads to the meaning and usage of the class.
4. Constructor class
The representation is the construction method in the class, generally like GetConstructors (), GetFields (), GetMethods () This, a look is known to be the plural, representing all.
The use of constructor directly to an example
These basic are fixed format, basically backrest, output:
5. Field class
As noted, field represents the member attribute. To do field class tests, create a new Fieldtest class first:
Take a direct look at the usage, continue to write the following code in Classtest:
Output:
Note: The difference between GetField () and Getdeclaredfield. Because a member property is private, one is public. GetField () Unable to discover private
Members, do not believe you can try. and for Getdeclaredfield (), if you do not set the back setaccessible (true), even if you can know that there is this field, but also
No use.
6. Practice Case One
Learning this, you can do a simple synthesis case: Change the value of all string-type properties in a class to a.
Output:
7. Method Class
Represents the member method, directly look at the example:
Output:
You can see the usage is also very simple, relatively straightforward. Next, for example, if you want to execute the main method in a class, you can refer to the following case:
This is not the first way to call directly because, in fact, we mainmethodtest this class might not be deterministic, but passed in by parameter:
Output:
8. Reflection of arrays
Here we first say a few concepts, arrays are also a class; Like a dimension, an array of the same type belongs to the same class:
Output:
Here's a question, how to use all the elements in the reflection output array:
Such :
Output:
It is not a problem to find a string, an array of type int or not, which involves the basic problem of package unpacking. No way, write a:
Output:
This is the downside, the basic usage of reflection is almost there. But many concepts have not been summed up, the time problem is not able. Can only learn the usage, the back is free
Then summarize the concept of understanding.
The reflection of the Java Foundation