Deep and shallow reflection

Time:2019-8-9

At the beginning of the concept of contact reflex, the mechanism of sensory reflex is very complex and difficult to understand, so in this article, the reflection mechanism of Java is summarized by personal understanding.

1. What is reflection?

What is reflection? It is said in the official documents that:

  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 technology is often used to detect and change the behavior of applications in Java virtual machines. It is a relatively advanced technology. Usually, the premise of its application is that the developers themselves have a strong understanding of the characteristics of the Java language. It’s worth noting that reflection is a powerful technical feature that enables applications to perform purposes beyond conventional means.

Personal Understanding: Reflection is a very powerful technology. The condition for using reflection is that the program ape is a great ape and has a good understanding of the characteristics of java. The power of reflection is that it can perform some unconventional operations.

Take a chestnut to illustrate:

After a moment’s thought, I think I can use the chestnut cooking as an illustration. I don’t know if it’s accurate (^,^). Usually we use rice cooker to cook at home. The steps of cooking are: cleaning rice – > drying the bottom of the pot – > putting the pot in the cooker – > closing the lid, electrifying, cooker work – > cooked rice, you can eat, but now there is a demand, I want to add an egg in the process of cooking, what happens now? What about the solution? Would you like to turn on the rice cooker that is cooking with electricity and put the eggs in it? In fact, the reflex is the same as the process of adding eggs just now. ____________. So the reflex is very strong. He does not play cards according to the usual routine. He does some small actions in the process of running the program in order to achieve the goal of “eating”. To add:This process can be regarded as coding and compiling process, “-> closing the lid, electrifying, cooker work” can be seen as the process of program operation, “-> cooked rice, you can eat” can be seen as the end of program operation.

 

2. Reflection mechanism in Java

2.1 Common Classes in Reflection

To understand the reflex mechanism, first of all, familiarize yourself with several categories:

1) Class class

Class class instances represent classes and interfaces in running Java applications. Class is the abstraction of ordinary classes, interfaces, enumeration classes, arrays, etc., that is, their type is Class, they are instances of Class.

Since Class represents classes and interfaces, we can use its instance (bytecode file) to get information about the corresponding classes or interfaces, such as annotations, modifiers, types, class names, attributes, methods, constructors, direct parent and child classes, etc. We can also create instances of Class, but only call nonparametric classes. Create methods to create.

What can’t understand? Chestnuts, for example, we all know that living things can be divided into animals, plants, microorganisms and viruses, while animals have people, Miao people, puppies, plants, microorganisms and viruses. Similarly, we can analogize that living things are classes, animals are common classes, plants are interfaces, microorganisms are enumerations, viruses are arrays (enumerations and arrays are special classes), and people, meows and puppies are familiar objects, as shown in the figure.

Now you can see that ordinary classes, interfaces, enumerations, arrays can actually be regarded as objects of Class.

2) Field class

Field represents the attributes of a class, which contain modifiers, types, attribute names, and values. So you can get modifiers, types, attribute names of attributes through an instance of Field, and you can modify the value of attributes.

3) Method class

Method represents member methods of a class, including annotations, modifiers, return types, method names, parameters, etc. So you can get information about the method through an instance of Method, such as annotations, modifiers, return types, method names, and you can call the method represented.

4) Constructor class

Constructor represents a constructor, which can obtain information about the constructor, such as modifiers, through an instance of Constructor, and create instances of its classes.

5) Modifier class

Modifier denotes modifiers by which information about modifiers, such as what modifiers to use, can be obtained.

6)Annotation

Annotation Represents Annotation

 

All of the above classes are in java. Lang

2.2 Method of Getting Class Objects

Knowing what reflex is, do you want to experience reflex?

If you want to show the operation, you must first get the Class object, because the Class object represents all kinds of classes, and then you can get all kinds of information about classes. The acquisition method is as follows:

1) Through object. getClass ()

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

Note: This method is not applicable to int, float, etc.

2) By (type name). class, wrapper class. Type

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

3) Through Class. forClass (fully qualified name of String class)

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

Which method to obtain depends on the actual situation.

2.3 Getting Class Information

With the Class object, you can get the class members (methods + attributes), annotations, class modifiers, and so on. As mentioned above, methods in Java are represented by Method classes, properties are represented by Field classes, annotations are represented by Annotation classes, and modifiers are represented by Modifier classes. Class classes have corresponding methods to get them. As follows:

2.3.1 Object for Getting Attribute Field

// Gets all attributes, but does not include attributes inherited from the parent class
// Gets the specified attribute declared in this class with the name of the attribute as the parameter
8 public Field getField(String name)

2.3.2 Getting Method Method Objects

// Gets the method specified in this class declaration. The first parameter is the name of the method, and the second parameter is the class of the method parameter type.
// For example, get setName (String name) method, getDeclareMethod ("setName", String. Class)

2.3.3 Get the Constructor object

// Gets the constructor specified in this class
 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
 // Gets the specified public constructor
 public Constructor<T> getConstructor(Class<?>... parameterTypes)
 // Get all the construction methods in this class
 public Constructor<?>[] getDeclaredConstructors() throws SecurityException 
 // Get all the public ownership constructions in this class
 public Constructor<?>[] getConstructors()

The acquisition of construction method is roughly the same as that of common method.

——————————————————————

The above methods are all in Class class, don’t be silly and don’t know (don’t ask me how I know > >), and then call through Class object.

Here is just a list of commonly used class information acquisition methods, other information acquisition methods, look at API documents, such as annotations, class objects (the amount seems to be a little around.) And so on.

 

2.4 Getting Class Membership Information

The above is just to get the objects of the class represented by the members of the class. We also need to use them or get the information of the members (name, modifier, etc.). Because there are objects representing members, it’s OK to call instance methods using objects.

2.4.1 Field class

Field classes can be roughly divided into two methods, one is to get information about attributes, the other is to set the value of attributes.

The first is:

// Returns the name of the field represented by this Field object
  String  getName() 
 // Returns a class object that identifies the declarative type Field object of the field represented. 
 Class<?>  getType() 
 // Returns the Java language modifier for the field represented by the Field object as an integer. Taking an integer as a parameter of Modifier's construction method, you can get the object of the modifier class represented by that integer.
 int  getModifiers() 
 ----------------------------------------------------------------
 
 // Gets the value of a static or instance field of type int, or converts it to another original type of type int by extension.
 int getInt(Object obj) 
 // Gets the value of a static or instance field of type long, or another basic type of value that can be converted to type long by enlarging the transformation. 
 long getLong(Object obj) 
 ... A bunch of methods to get ** (Object obj) are omitted here. What are the basic types of attributes? Just get what you want.
Property is a reference type, so call the following method
// Returns the Field of the field represented, on the specified object. Object get (Object obj)

The second is:

// Sets the value of double as a field on the specified object.  
 void setDouble(Object obj, double d) 
 // Sets the value float specified as a field on the object.  
 void setFloat(Object obj, float f) 
 // Sets the value of int as a field on the specified object.
 void setInt(Object obj, int i) 
 Here, we omit a bunch of set **() methods, just set what is the basic type of attribute.
 Property is a reference type, so call the following method
 // Sets the field represented by this Field object on the specified object parameter to the specified new value.
 void  set(Object obj, Object value)
Note: If there is no access permission, the default property value can not be set, then what? Is it that you can't operate? Nevertheless, as I said earlier, the reflection is very powerful, and some unconventional operations can be performed.
At this point, we call setAccessible (true) of the Class object.
) The method is OK!
Do you think reflection can be very strong?

2.4.1 Method Class

The main method of method class is to get the information of method.
Partial methods:
Int getModifiers ()// Returns the Java language modifiers of the executable file represented by the object.  
 String getName ()// Returns the name of the method represented by the method object as String.  
 Annotation [][] getParameterAnnotations ()// Returns an array of Annotation s representing the order in which the formal parameters of Executable are declared represented by the object.  
 Int getParameterCount ()// Returns the number of formal parameters (either explicit or implicit) of the executable represented by this object.  
<?>[] getParameterTypes ()// Returns an array of class objects that represent the formal parameter types of the executable file represented by that object in declarative order.

2.4.1 Constructor class

The main method of Constructor class is to obtain the information of construction method and create object.

Get method information:

Int getModifiers ()// Returns the Java language modifiers of the executable file represented by the object.  
 String getName ()// Returns the name of this constructor as a string.  
 When Annotation [][] getParameter Annotation s ()// returns an array of Annotations representing parameters annotates s s, the object representation declares the order of Executables.  
 Int getParameterCount ()// Returns the number of formal parameters (either explicit or implicit) of the executable represented by this object.  
 Class <?>[] getParameterTypes ()// Returns an array of class objects that represent the formal parameter types of the executable file represented by that object in declarative order.

Let’s leave the method of creating objects to the back.

2.5 Reflection creation objects and invocation methods

2.5.1 Creating Objects for Common Classes

There are two ways to create objects of common classes

The first is the method of calling Class objects

// First get the Class object
 Class clazz=Class.forClass("test.Student");
 // Create Objects
 Student stu=(Student)clazz.newInstance();
Note: This method can only create objects of classes of parametric constructors

Second: New Instance () method through Constructor

// First create the Class object
 Class clazz=Class.forClass("test.Student");
 // Get the constructor you want to call
 Constructor constructor=clazz.getConstructor(String.class, int.class);
 // Calling Constructor's newInstance () method
 Student stu= (Student) constructor. newInstance ("King", 20);

2.5.2 Create arrays

Array is essentially a Class, and there is a method in Class to identify whether it is an array or not.

Reflection creates arrays by Array. newInstance (T. class, dimension).

The first parameter specifies the element type in the array, followed by the variable parameter, which represents the array length limitation of the corresponding dimension.

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

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

2.5.3 Call Method

With the above methods, there are Class objects, Method objects, and examples. Now everything is ready, and it is only due to the East Wind.

So how do we call methods? There is such a method Object in the Method class.Invoke (Object obj, Object... args), object as instance object, args as parameter of calling method

A chestnut:

Class <?> C = Class. forName ("com. kal01. reflect05. Person"); // Get Class object
 Person P1 = (Person) C. newInstance (); // Get an instance
 Method m3 = C. getDeclared Method ("test"); // fetch method
 M3. setAccessible (true); // / When there is no access, just set it up.
 M3. invoke (p1);// Call method
 M3. setAccessible (false); // Modified access rights, remember to change back

2.6 Static and Dynamic Loading

Seeing whether there is a question here, it seems that the method of invoking a class by reflection is not different from that we usually call except for its complexity. Why do you make such a fuss?

So let’s briefly talk about static loading and dynamic loading.

Looking back at the chestnut that was cooked before, the example of static loading is somewhat similar to that of dynamic loading.

Static Loading: When we use classes in programs, static loading requires that the classes to be used must exist at compile time, otherwise the compiler will fail to run the program. This error often occurs when you forget to import a package when encoding.

Dynamic Loading: Using reflection to load classes (i.e. to get Class objects) does not require us to have the class we want to use at compile time. When the program runs, we can look for classes (from jar packages, networks, etc.) and then load classes into the method area. If we do not find this class, ClassNotFoundException will be thrown. Abnormal.

There are plans and facts:

Now you can see that reflection is the most powerful thing. When using reflection class, it is not necessary for this class to exist in the compiler. This increases the flexibility of the program and completes our saucy operation.

In conclusion:

When using reflection, remember a good word: Hold on, man, don’t roll over!