Reflected in simple terms

Just getting started with the concept of reflection, I feel this reflex mechanism is very complex difficult to understand, so in this article for java reflection mechanism to personal understanding summarized.

1. What is a reflection?

What is reflection? In the official documentation had this to say:

  Reflection is commonly used by programs which require the ability to examine ormodify the runtime behavior of applications running in the Java virtual machine. 
This is a relatively advanced feature and should be used only by developers whohave a strong grasp of the fundamentals of the language.
  With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible

translate:

   Reflection technique is often used to detect and change the behavior of applications in the Java virtual machine performance. It is a relatively more advanced technology, as long as it is usually applied to develop themselves for the Java language features have a strong understanding of the basis. It should be noted that the reflection characteristic is a powerful technique, so that the application can perform a number of conventional means can not match the object.

Personal understanding: Reflection is a very cattle x technical conditions using reflection is a program ape ape is a big, very understanding of the characteristics of java. Reflected Niubi is that he can do some unconventional operations.

For chestnut to explain:

  A little thought for a moment, think that using this cooking chestnuts to illustrate it, I do not know about the accuracy (^, ^). Usually we are at home is generally used to cook the rice cooker, cook the general steps are: Wash rice -> Dry the bottom of the pot -> Put the pan into the rice cooker -> Close the lid, electricity, rice cookers work - -> rice is cooked, you can eat, but now there is a demand, I want to add an egg in the process of cooking in, then how to solve it? While power is not open cooking rice cooker, then put the eggs go? (Demand for goods from eating ^ _ ^) In fact, the process of reflection is equivalent to just add eggs. So reflecting very fast hardware, he is not the usual routine the cards, do little things in the course of the program running, in order to achieve "food goods". Add: "Wash rice -> Dry the bottom of the pot -> Put the pan into the rice cooker ->" This process can be seen as encoding the compilation process, "-> Close the lid, electricity, rice cookers work" can be seen do is to run the process, "-> rice is cooked, you can eat" can be seen as the end of the program run.

 

The reflection mechanism 2.java

2.1 reflective common class

Understanding the reflection mechanism, first familiarize yourself with a few categories:

1) Class Class

Class instance of the class represent classes and interfaces Java applications running in. Class is the general abstract class, interface, enum type, such as an array, i.e., their type is Class, which is an example of the Class.

Since Class represent classes and interfaces, then we can obtain a corresponding class information through his or interface instance (byte code files), such as: annotation, modifiers, type, class name, property, method, constructor, direct parent and child classes, etc., and can create an instance of it, but can only call the constructor with no arguments to create.

What can not read? For chestnuts, we all know, it can be divided into biological animals, plants, microbes and viruses, and animals someone, meow star people, dogs, etc., plants, microbes and viruses, too. Similarly, we can look at the analogy, is the biological Class, animals are common, plant is the interface, the microorganism is an enumeration class virus is an array (array and enumeration is a special class), but man, meow star people, our puppy familiar objects, as

Oh, the whole understand it, the ordinary classes, interfaces, enumerations, in fact, can be used as an array of Class objects.

2) Field class

   Field represents class attributes, attribute containing modifiers, types, attribute names and values. It is possible to obtain modifiers, types, attribute by attribute name Field of the examples, and may modify the value of the attribute.

3) Method class

   Method class represented member methods, the method comprising annotations, modifiers, return type, method name, parameters and the like. It may be obtained by the method of Method instance information, such as annotations, modifiers, return type, and the method represented by method name can be called.

4) Constructor class

   Constructor represents constructor, configured to obtain information by way of example the Constructor methods, e.g., modifiers and the like, and it can create an instance of the class through it.

5) Modifier class

    Modifier represents modifiers, modifier information may be acquired by it, what the modifier like e.g.

6)Annotation

  Annotation behalf comment

 

In the above classes are in java.lang

2.2 acquire Class object methods

Understand what is after reflection, I am not also want to experience the show reflected this operation?

Want to show, you first get a Class object, because Class object on behalf of a variety of classes, then with it before they can get a variety of information classes. Acquisition method as follows:

1) object.getClass ()

1 public static void main(String[] args) {
2         
3         Car car = new Car();
4         
5         Class clazz = car.getClass();
6     }

NOTE: This does not apply int, float type, etc.

2) (type name) .class, packaging .Type

1 public static void main(String[] args) {
2         Class clazz = Car.class;
3         Class cls1 = int.class;
4         Class cls2 = String.class;
5         Class cls3=Iteger.Type
6     }

3) by Class.forClass (String class fully qualified name)

1 try {
2     Class clz = Class.forName("com.frank.test.Car");
3 } catch (ClassNotFoundException e) {
4     e.printStackTrace();
5 }

Which method to get to see the actual situation.

2.3 obtain class information

Once you have Class object, you can get members (methods + properties) class, class notes and modifiers and the like. I said above, java method represented by Method class attribute represented by the Field class, Annotation class annotated with said modifier represented by the Modifier class. Class class has a corresponding method to obtain them. as follows:

2.3.1 Field object acquired property

1  // get all the attributes, including but not inherited from the parent class of the attribute 
2  public Field, [] getDeclaredFields () throws a SecurityException 
 . 3  // get all the public properties of its own, including inherited from parent classes down. 
. 4  public Field, [] getFields () throws a SecurityException 
. 5 // Get the specified property parameters declared in this class name attribute . 6 public Field, getDeclaredField (String name) . 7 // Get the specified public property, including the parent class , argument is the name of the
8 public Field, getField (String name)

2.3.2 Method object acquisition method

// Get the specified process according to the class declaration, the first parameter is the name of the method, the latter method is the parameter type parameter class 
// Get as setName (String name) method, getDeclareMethod ( "setName", String.Class )
public method, getDeclaredMethod (String name, class <?> ... the parameterTypes) // access to public, comprising the parent class public method, getMethod (String name, class <?> ... the parameterTypes) // Get this class all methods declared public method, [] getDeclaredMethods () // Get all public methods, including the parent class public method, [] getMethods ()

2.3.3 Gets constructor Constructor object

1  // Get constructor class specified in this 
2  public the Constructor <T> getDeclaredConstructor (Class <?> ... The parameterTypes)
 . 3  // Get the specified public constructor 
. 4  public the Constructor <T> getConstructor (Class <?> . the parameterTypes ..)
 . 5  // Get all this class constructor 
. 6  public the constructor <?> [] getDeclaredConstructors () throws a SecurityException 
 . 7  // Get all the public in this class constructors 
. 8  public the constructor <?> [] getConstructors ( )

Obtaining substantially the same as the conventional method of obtaining constructor.

------------------------------------------------------------------

The above methods are in Class class, do silly do not know (do not ask how I know> _>), then the Class object by calling on it.

Just to name a commonly used class of information acquisition method, other method for obtaining information, see the API documentation of it, such as notes, Class of object class (the amount seems a bit around ...) and so on.

 

2.4 class members to obtain information

The above are just objects acquired on behalf of class members of the class, we have to use them to obtain information or a member of (name, modifiers, etc.). Because the object on behalf of members, using an object instance method is invoked on it.

2.4.1 Field class

The method of the Field class can be divided into two types, one is to obtain information about the properties, the other one is set value of the property.

The first:

1  // Returns the field object is thus represented by the Field name 
2  String getName () 
 . 3  // Returns a class object representation of this field identifies the type of statements Field object. 
4 Class <?>   GetType () 
 5  // Returns the field represented by this Field object in the Java language modifiers, as an integer. Integers as parameters to the constructor Modifier, you can obtain the integer representing the object class of modifiers 
. 6  int   getModifiers () 
 . 7 --------------------- -------------------------------------------
 8  
9  // get type static or instance field value of the int, or converted to other values of the original types by extending the conversion int. 
10  int the getInt (Object obj) 
 . 11  // Get value of type field long static or instance of, or obtaining other values may be converted to the basic types of long by expanding type conversion. 
12  Long getLong (Object obj) 
13 omitted pile get here ...... ** (Object obj) methods, properties, what is the basic type, what you get on the line
 14 property is a reference type, then call the following method
15  // Returns Field of the field represented by the specified object.  16 Object GET (Object obj)

The second:

1  // Set the double value of a field as specified object.  
2  void setDouble (Object obj, Double D) 
 . 3  // disposed on the object specified as a float value field.  
. 4  void setFloat (Object obj, a float F) 
 . 5  // set the value of a field as specified object int. 
6  void setInt (Object obj, int i) 
 7 ........ omitted here a bunch of set ** () method, the basic type attribute is what you set what on the line
 8  property is a reference type, then call the following methods
 9  // field is set to this field object on the specified object to the specified parameter represents the new value. 
10  void   SET (Object obj, Object value) 
Pay attention to you: If you do not have access, the default is not set property values, how to do it? It is not on the show can not operate? However, earlier also it said, reflected very fast hardware, may be some unconventional operations, 
then we call the Class object setAccessible (to true
) method on it!
Is not that a strong reflection can?

2.4.1 Method Class

Method The method is mainly based information acquisition method is 
part of the method:
1  int getModifiers () // return the executable file represented by this object in the Java language modifiers.  
2 String getName () // Returns the name of the method whereby the objects represented by methods, as String.  
. 3 the Annotation [] [] getParameterAnnotations () // Returns an array of arrays Annotation s, expressed in the form of Executable declaration order Executable parameter represented by this object.  
4  int () getParameterCount // number of formal parameters return this object represents the executable file (either explicit or implicit statement declarations).  
. 5 Class <?> [] GetParameterTypes () // Returns an array of class objects in the class declaration order parameter representation of the type of executable file represented by this object.  

2.4.1 Constructor class

Constructor methods mainly based access to information and a method to create an object configuration

Method for obtaining information:

1  int getModifiers () // return the executable file represented by this object in the Java language modifiers.  
2 String getName () // Returns a string constructor name.  
. 3 Annotation [] [] getParameterAnnotations () // -shaped array represents an array Annotation return reference annotate s, Executable declaration order, the object of FIG.  
4  int () getParameterCount // number of formal parameters return this object represents the executable file (either explicit or implicit statement declarations).  
. 5 Class <?> [] GetParameterTypes () // Returns an array of class objects in the class declaration order parameter representation of the type of executable file represented by this object.

I will not speak of ways to create an object into the back to go.

2.5 reflection to create objects and invoke methods

2.5.1 Creating the object of general category

Create a common class of objects can be divided into two methods

The first: call the Class object methods

4  // First get the Class object 
5 Class clazz = Class.forClass ( "test.Student" );
 6  // create the object 
7 Student STU = (Student) clazz.newInstance ();
Note: This method can only create object class constructor without parameters

The second: by the newInstance Constructor () method

1  // First create a Class object 
2 Class clazz = Class.forClass ( "test.Student" );
 3  // get the constructor want to call 
4 Constructor constructor = clazz.getConstructor (String. Class , int . Class );
 5  / / invoke the Constructor newInstance () method 
. 6 Student STU = (Student) Constructor.newInstance ( "king", 20);

2.5.2 Creating an array

The array is a Class nature, and there is a method used to identify whether it is a Class in the array.

Reflective arrays are created by Array.newInstance (T.class, dimension) this method.

The first argument specifies the type of an element within an array, the latter is a variable parameter representing the respective dimensions of the array length limit.

For example, I want to create an int [2] [3] array.

1 Int[][]  a=Array.newInstance(Integer.TYPE, 2, 3);

2.5.3 calling method

With the above method, there is a Class object, there are ways Method object, there are instances, now everything is ready, only a strong wind.

Then how do we call the way to do that? In the Method class has such a method Object  invoke(Object obj, Object... args),object为实例对象,args为调用方法的参数

To a chestnut:

. 1 <?> Class C = the Class.forName ( "com.kal01.reflect05.Person"); // Get Class object 
2 the Person P1 = (the Person) c.newInstance (); // Get Example 
. 3 Method, M3 = C. getDeclaredMethod ( "the Test"); // acquisition method 
4 m3.setAccessible ( to true ); // when there is no access, you can set about 
5 m3.invoke (p1); // call the method 
6 m3.setAccessible ( false ) ; // modify the access, modification remember back

2.6 static loading and dynamic loading

See here is not a question, call the class method reflecting complex than it seems in addition, we usually call with no difference. Why get so fancy?

So here briefly about the static loading and dynamic loading.

Recall that chestnuts before cooking, static load and dynamic load of this example is somewhat similar.

Static load: When we use the class in the program, the static load requirements of the class is to be used must require the presence of at compile time, or the compiler error, can not run the program. When the lead pack forget, this often occurs when the coding error.

Dynamic load: use reflection to load classes (ie get Class object), does not require us to exist of that class, if used at compile time, the program is running, only to find class (you can find from the jar package, network, etc.), then class is loaded into the method area, if not find this class will throw a ClassNotFoundException.

There are pictures and the truth:

This time of reflection seen at fast hardware of the bar, when using reflection using the class, the class does not need to exist in the compiler, which increases the flexibility of the program, the completion of our Sao operation!

To sum up:

When using reflection, remember a good word: brother, stabilize, do not roll!

 

Guess you like

Origin www.cnblogs.com/ironHead-cjj/p/11312545.html