Advanced Java's reflection

First, the concept of reflection

        Java reflection mechanism means that: in the operating state, for any class, are made known to all properties and methods of this class; for any object, are able to call any of its methods and properties; this information is acquired dynamically, and dynamic call the object's method function called reflection mechanism of Java language.

        Reflection provides a more flexible way to create objects , get information of the object. As the Spring the IoC, the AOP the Spring , dynamic proxies , are based on reflection.

Reflective understanding:

        Under normal circumstances, we use a class must know what it is like, is used to do. So we directly instantiate this class, then use the class object to operate:

Phone phone = new Phone(); 
phone.setPrice(4);

        The reflection is not initially know what I want to initialize the class object is, naturally, can not use the new keyword to create the objects. At this time, we use the reflection API JDK provided by reflex call:

Class clz = Class.forName("com.xxp.reflect.Phone");
Method method = clz.getMethod("setPrice", int.class);
Constructor constructor = clz.getConstructor();
Object object = constructor.newInstance();
method.invoke(object, 4);

        The results of the above two pieces of code, in fact, is exactly the same. But the idea is completely different, the first paragraph of the code is not running already identified class (Phone) to run, and the second piece of code is learned that the class to run (com through the string value at runtime .xxp.reflect.Phone).

        So what is reflection? What type of reflection is known at runtime will be operated, and can be constructed for a complete class at runtime, and corresponding method call.

Reflecting usage scenarios:

        In everyday third-party application development process, often encounter a member variable of a class, method or attribute is private or open only to system application , this time you can take advantage of Java's reflection mechanism by reflection get private members or desired method.

Reflecting benefits:

  • May be the program is running, the operation of these objects.
  • Decoupling can improve the scalability of the program.

Reflection of applications:

        Can be used to design the framework of the principle of reflection, if we only want to modify the configuration file can be created to achieve the object class and perform the appropriate method, it can be achieved by reflection. For example: Spring Framework.

 

Second, the principle of reflection

        To understand the principle of reflection, we must first understand what type of information . Let's Java runtime information identifying objects and classes, there are two ways: one is the traditional RTTI (the Run-Time Type Identification), it assumes that we compile time already know all the types of information; another it is a reflection mechanism , which allows us to run-time discovery and use of information classes.

        RTTI is required to compile the class is known, it is because you want to open and compile-time checking Class file , which is Class.forName ( "name"). must exist in the file name is the name of the class file path of the current classpath , that is, at compile time, the compiler must know all the classes through RTTI handled. When Class file is not available at compile time, it must rely on reflection to open and check Class file at run time.

        Whether RTTI or reflection, used a prerequisite: you must first obtain the Class object.

        First, look at the class loading process:

        

        Loading class, Java code, has gone through three stages, and each stage, we can go to obtain the corresponding Class object according to the characteristics of the stage.

        

        Java code has gone through three stages:

  • Source source stage: At this bytecode files (Class files) is not loaded into memory, we must be manually loaded to generate a Class object, so we need Full class name (package name + class name) generated Class object this method may throw a ClassNotFoundException;
  • Class class object stage: At this point bytecode file has been loaded into memory, so there will be a class name , so we just need to get through the Class object class name of the class attribute;
  • Runtime Runtime Phase: At this point the object has been created, so we can use the method of the object to get the Class object.

        To sum up, get Class object in three ways :

(1) Class.forName ( "full class name") : the bytecode file loaded into memory, the object return Class;

         Be used: used for the configuration file , the class name is defined in the configuration file, read the file and load the class. For example: JDBC driver is loaded

(2) the class name .class : class obtained by class name attribute;

         Be used: used for passing parameters

(3) Object .getClass () : getClass () methods defined in the class Object.

         Be used: used for obtaining the object bytecode manner

        Note: the same byte code file (* .class) during the operation of a program will only be loaded once, no matter which way acquired by Class objects are the same.

        

Third, the common reflection API

1. Class Object

  • Acquiring member variables are:

                * Field [] getFields (): Gets all public member variables modified
                * Field getField (String name): Gets modified to specify the name of the public member variables

                * Field [] getDeclaredFields (): Gets all member variables, regardless of modifiers
                * Field getDeclaredField (String name): Gets the member variables specified name  

  • Obtaining construction method are:

                * Constructor<?>[] getConstructors()  
                * Constructor<T> getConstructor(类<?>... parameterTypes)  

                * Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)  
                * Constructor<?>[] getDeclaredConstructors()  

  • The method of obtaining the members are:

                * Method[] getMethods()  
                * Method getMethod(String name, 类<?>... parameterTypes)  

                * Method[] getDeclaredMethods()  
                * Method getDeclaredMethod(String name, 类<?>... parameterTypes)  

  • Get full class name:    

                * String getName()  

2. Field member variables

  • Settings:

                * void set(Object obj, Object value)  

  • Get the value:

                * get(Object obj) 

  • Ignore safety checks access modifier :

                * SetAccessible (true): Violence reflection

3. Constructor Constructor

  • Create an object:

            * T newInstance(Object... initargs)  

        Note: If you create an object with an empty argument constructor, the operation can be simplified: the newInstance Class object methods

4. Method Object Method

  • Execution method:

            * Object invoke(Object obj, Object... args)  

  • Acquisition method name:

            * String getName: acquisition method name

 

Fourth, reflecting summary

new objects and reflected objects obtained difference

  • When using the new, the class can not be loaded, may have been loaded; while when using reflection, it is necessary to ensure that the class is already loaded and connected .
  • new keywords can call any public constructor; and reflection can only call the constructor with no arguments.
  • new keywords are strongly typed, a relatively high efficiency; and the reflective type is weak and inefficient .

 

Published 67 original articles · won praise 69 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34519487/article/details/104339968