Java reflection depth analysis

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 ()

public static void main(String[] args) {
       
        Car car = new Car();
       
        Class clazz = car.getClass();
    }

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

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

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

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

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

2.3.2 Method object acquisition method

// Get method of the specified 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

 // Get This class constructor specified
public the Constructor <T> getDeclaredConstructor (Class <?> ... The parameterTypes)
// Get the specified public constructor
public Constructor <T> getConstructor (Class <?> ... parameterTypes)
// Get all this class constructors
public the constructor <?> [] getDeclaredConstructors () throws a SecurityException
// Get all this class public constructors
public 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:

// Returns the field thus Field object represents the name of the
 String getName ()
// returns a class object that identifies the declared type Field object field of this representation.
Class <?> GetType ()
// 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 of the class modifiers
int getModifiers ()
----------------------- -----------------------------------------

// Get the value of the static or instance field type int or converted to the value of another original types by extending the conversion int.
the getInt int (Object obj)
// Get the value of static or instance field type of long or another basic types of values obtained can be converted to type long by expanding the conversion.
getLong Long (Object obj)
...... here omission pile method get ** (Object obj) of the basic properties of what type, what you get on the line
14 is a reference type attribute, then call the following method
/ / field returns the field represented by the specified object. 16 Object get (Object obj)

The second:

// Set the double value of a field as specified object. 
setDouble void (Object obj, Double D)
// float is provided on the value of a field as specified object. 
setFloat void (Object obj, a float F)
// set the value of a field as specified object int.
setInt void (Object obj, int i)
........ omitted here a bunch of set ** () method, the property is set on what basic type on the line
property is a reference type, then call the following method
/ / field object of this field is set to the specified object on the specified parameter represented by the new value.
void set (Object obj, Object value )

Pay attention to you: If you do not have access, the default is not set property values, then 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

 // First create Class objects
Class clazz = Class.forClass ( "test.Student");
// Gets want to call the constructor
Constructor constructor = clazz.getConstructor (String.class, int.class);
// Constructor invocation of newInstance () method
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:

<?> Class c = Class.forName ( "com.kal01.reflect05.Person"); // Get Class object
Person p1 = (Person) c.newInstance ( ); // Get instance
Method m3 = c.getDeclaredMethod ( " test "); // get method
m3.setAccessible (true); // when there is no access, you can set about
m3.invoke (p1); // call the method
m3.setAccessible (false); // modify access permissions, modify 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 at compile time, which increases the flexibility of the program, the operation can be completed our show!

To sum up:

When using reflection, remember one sentence: brother, stabilize, do not roll!

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160201.htm