reflection, at that time often listen to them, they have seen some information, but also may be used in design mode, but it does not feel a more in-depth understanding, this time to re-learn a bit, feel OK!
first, take a look at the concept of reflection:
It is the ability of a program to access, detect and modify its own state or behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.
Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled again at runtime without the need for source code linking between components. But the use of reflection is expensive!
look at the concept is very faint, continue to look down.
Two, the effect of reflection mechanism:
1, decompile:. Class-->.java
2, through the reflection mechanism to access the Java object Properties, methods, construction methods, etc.;
this seems to be easier to understand, and below we look at how to implement these features.
Three, let's take a look at Sun . The classes in the reflection mechanism are provided for us:
Java.lang.Class;
Java.lang.reflect.Constructor; Java.lang.reflect.Field;
Java.lang.reflect.Method;
Java.lang.reflect.Modifier;
Many of the methods in reflection, attributes, and so on, we can query from these four classes. Or what sentence to learn the constant query API, that is our best teacher.
Four, the specific function realization:
1, the reflection mechanism gets the class there are three ways to get the Employee type
[Java]View PlainCopy print?
- The first way:
- CLASSC1 = Class.forName ("Employee");
- The second way:
- Each type in Java has a class attribute.
- CLASSC2 = Employee. class;
- The Third Way:
- Any Java object in the Java language has a GetClass method
- employeee = new Employee ();
- CLASSC3 = E.getclass (); //C3 is the runtime class (the run-time class for E is employee)
2, create object: Get the class later we'll create its object, using the newInstance:
[Java]View PlainCopyprint?
- Class c =class.forname ("Employee");
- Create a new instance of the class represented by this class object
- Objecto = C.newinstance (); //Call the No-parameter construction method for employee.
3, Gets the attribute: is divided into all attributes and the specified properties:
A, let's look at the notation for all the attributes:
[Java]View PlainCopyprint?
- Get the entire class
- Class C = class.forname ("Java.lang.Integer");
- //Get all the properties?
- field[] fs = C.getdeclaredfields ();
- //define variable-length strings to store properties
- StringBuffer sb = new StringBuffer ();
- //Stitch each property into this string by appending the method
- //Outermost public definition
- Sb.append (Modifier.tostring (C.getmodifiers ()) + "class" + c.getsimplename () +"{\ n");
- //each property inside
- For (Field field:fs) {
- Sb.append ("\ t"); Space
- Sb.append (Modifier.tostring (Field.getmodifiers ()) +""); Gets the modifier for the property, such as Public,static, and so on
- Sb.append (Field.gettype (). Getsimplename () + ""); The name of the type of the property
- Sb.append (Field.getname () +"; \ n"); Name of property + carriage return
- }
- Sb.append ("}");
- System.out.println (SB);
b, get specific attributes and compare the traditional methods to learn:
[Java]View PlainCopyprint?
- Public static void Main (string[] args) throws exception{
- <span style="White-space:pre" > </span>//Previous way:
- /*
- User U = new user ();
- U.age = 12; Set
- System.out.println (U.age); Get
- */
- //Get class
- Class C = class.forname ("User");
- //Get id attribute
- Field IdF = C.getdeclaredfield ("id");
- //Instantiate this class to assign O
- Object o = c.newinstance ();
- //Break Package
- Idf.setaccessible (true); //Using the reflection mechanism can break the encapsulation and cause the properties of the Java object to be unsafe.
- //Assign the id attribute of the O object to "Max"
- Idf.set (O, "110"); //set
- //get
- System.out.println (Idf.get (o));
- }
4, get the method, and the construction method, no longer described in detail, just look at the keyword:
Method keyword |
Meaning |
Getdeclaredmethods() |
Get all the methods |
Getreturntype() |
Get the return type of the method |
Getparametertypes() |
Get the incoming parameter type for a method |
Getdeclaredmethod ("Method name", Parameter type. Class,......) |
Get a specific approach |
|
|
Constructor method keyword |
Meaning |
Getdeclaredconstructors() |
Get all the construction methods |
Getdeclaredconstructor (parameter type. Class,......) |
Get a specific construction method |
|
|
Parent class and Parent interface |
Meaning |
Getsuperclass() |
Gets the parent class of a class |
Getinterfaces() |
Get an interface for a class implementation |
This allows us to get the various contents of the class and decompile it. For JAVA , which compiles and then runs the language, the reflection mechanism can make the code more flexible and easier to implement object-oriented.
Five, Reflection plus config file, make our program more flexible:
in the design mode of learning, learning the abstract factory when the reflection to more convenient reading database link string, etc., was not too understanding, then copied. Take a look at the use of reflection + configuration files in . NET:
the configuration file used at that time is the app. config file, which is in XML format and fills in the contents of the linked database :
[HTML]View PlainCopyprint?
- <configuration>
- Lt;appsettings>
- <add key= "" value= " "/>
- Lt;/appsettings>
- </configuration>
The notation of reflection:
[CSharp]View PlainCopyprint?
- Assembly.Load ("Name of the current Assembly"). CreateInstance ("Current namespace name"). The class name to instantiate);
The advantage is that it is easy for us to change the database, for example, we upgrade the system database from SQL Server to Oracle, then we write two copies of the D layer, change the contents of the configuration file, Or add the conditions to choose a bit, bring a lot of convenience.
Of course,the same is true in JAVA, except that the configuration file here is . Properties, called a properties file. Reads the contents of the inside through reflection. This code is fixed, but the contents of the configuration file we can change, so that our code a lot of flexibility!
In summary, theJAVA reflection of the re-learning, flexible use of it, can make our code more flexible, but it also has its shortcomings, is to use it will make our software performance is reduced, complexity increases, so we also need to use it carefully.
View of the Java reflection mechanism