The reflection mechanism of Java (important)

Source: Internet
Author: User

1, the concept of reflection

Java reflection mechanism is in the running state , for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.

Java program loading process: source files. Java---compiled (javac.exe)---get one or more. class files---rerun (java.exe)---will load the classes that need to be used (through the JVM's ClassLoader)---. Class When loaded into memory, the JVM automatically instantiates a class object based on the. class, which corresponds to. class one by one (that is, a class is a Java.lang.Class object)---and then creates an object of that class from a class object.

So: Java.lang.Class is the source of reflection.

1) An instance of Java.lang.Class represents classes and interfaces in a running Java application. That is, there are more than n instances of the JVM in each class that has the class object. (including basic data types)

2)Java.lang.Class There is no public constructor method. Classobjects are constructed automatically by the Java virtual machine and by calling methods in the class loader when the class is loaded defineClass . That is, we do not need to deal with the creation ourselves, the JVM has helped us to create a good.

2. Advantages and disadvantages of reflection

Static compilation: Determines the type at compile time, binds the object, which is passed.
Dynamic compilation: The runtime determines the type, binding object. Dynamic compilation maximizes the flexibility of Java and embodies the application of polymorphism, which reduces the coupling between classes.

the advantages of the reflection mechanism: It can achieve dynamic creation of objects and compile, showing great flexibility (especially in the development of Java EE, its flexibility is very obvious). Through the reflection mechanism, we can obtain the various contents of the class and decompile it.

the drawback of the reflection mechanism is that it has an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVM what we want to do and let it meet our requirements. This type of operation is always slower than performing the same operation directly.

3, Reflection Usage 3.1, get the three methods of Java.lang.Class object
    1. Call its GetClass () method through the object of the run-time class
    2. Call the. Class property of the run-time class
    3. Call the static method of class forname (String className). This method is reported classnotfoundexception
 Public class Student {}
 Public classReflect { Public Static voidMain (string[] args) {//(1) call its GetClass () method through the object of the run-time classStudent STU1 =NewStudent ();//This new creates a student object, a class object. Class Stuclass = Stu1.getclass ();//Get Class objectSystem.out.println (Stuclass.getname ()); //(2) Call the. Class property of the run-time classClass stuClass2 = Student.class; System.out.println (Stuclass= = StuClass2);//determines whether the first method gets the class object and the second method gets the same//(3) Call class's Static method Forname (String className). This method is reported ClassNotFoundException        Try{Class STUCLASS3= Class.forName ("com.jp.Student");//Note that this string must be a true pathSystem.out.println (STUCLASS3 = = StuClass2);//determine if three ways to get the same class object}Catch(ClassNotFoundException e) {e.printstacktrace (); }    }}

Description

1) During run time, a class that has only a single class object is generated. The above three methods are to go to memory to get this student class (i.e. an instance of Java.lang.Class)

2) If the student class is wrong, the 12th compile error (the compiler will be the Java source code for lexical analysis, syntax analysis, semantic analysis and other steps to compile into bytecode); The third compile time will pass, but the runtime will error; This means that the third is dynamic compilation .

For illustration 2) to do an experiment.

The first step: Change the student class to the wrong

 Public class Student {    int a = gg;//is obviously wrong}

Step two: Separately running the reflect class three methods to get class instance objects

Two classes involved before running

The result of running the first method alone: compilation error. The description also compiles the Student.java, which is generated if the student class has no errors. Class (Run the second method separately as the first result)

The result of running the third method alone: the compilation succeeds, stating that the compile time does not compile the class in Class.forName ()

3.2, what can be done with the Java.lang.Class instance (that is, the runtime class of other classes except Class)

3.2.1 Apply one: You can create an object of the corresponding runtime class

// method One: class's Newinstanc () method @Test    Public void throws exception{      = Class.forName ("Com.jp.Animal");  Get the class instance (i.e. run-time Class)      = clazz.newinstance (      ); = (Animal) obj;      System.out.println (a);  }
//method Two: Class Getdeclaredconstructor () method, get the specified constructor, and then use the Newinstance () method of the constructor@Test Public voidTest2 ()throwsexception{Class clazz= Animal.class;// Get the class instance (that is, the runtime Class) Constructor cons= Clazz.getdeclaredconstructor (String.class,int.class);// Here is consistent with the above, objects have class instances, including basic data types, strings, etc. cons.setaccessible (true); Animal a= (Animal) cons.newinstance ("Tom", 10);    System.out.println (a); }

3.2.2 Application Two: invokes the specified structure in the corresponding runtime class (a specified property, method, constructor, etc.)

1) Get the construction method

Method of Batch:

Public constructor[] Getdeclaredconstructors (): Gets all the construction methods (including private, protected, default, publicly)

gets a single method, and calls:  

Public Constructor getconstructor (Class ... parametertypes): Gets a single "common" construction Method:

Public Constructor getdeclaredconstructor (Class ... parametertypes): Gets the "one constructor method" can be private, or protected, default, communal;

2) Get member variables

Batch of

Field[] GetFields (): Get all the "public fields"

Field[] Getdeclaredfields (): Gets all fields, including: Private, protected, default, public;

Gets the individual

public field GetField (String fieldName): Gets a "common" field;

public field Getdeclaredfield (String fieldName): Gets a field (can be private)

3) How to obtain

In bulk:

public method[] GetMethods (): Gets all the common methods, (the method containing the parent class also contains the object class)Public method[] Getdeclaredmethods (): Gets all the member methods, including private (not including inherited)to get a single:Public Method GetMethod (String name,class<?> .... parametertypes)
    • Parameters:
    • Name: Method name;
    • Class ...: Class type object of formal parameter

Public Method Getdeclaredmethod (String name,class<?> .... parametertypes)

Call Method:Method--public object invoke(object Obj,object ... args):
    • Parameter description:
    • OBJ: The object to invoke the method;
    • Args: Arguments passed when invoking a method
Method m = Stuclass.getmethod ("Show1", String.  Class); // get the instance object of the run-time class method System.out.println (m); // instantiate a Student object Object obj == M.invoke (obj, 20); // requires two parameters, one for the object to invoke (reflection), and one for the argument (the parameter required by the M method)

If the instance object of the obtained method is a static method, when the static method is run,. Invoke (null,20), the object type can write null.

4, typical applications

1) dynamic Proxy in proxy design mode

Dynamic Proxy: Dynamically creates a proxy class, based on the proxy class and the interfaces it implements, while the program is running. When invoking an abstract method of the implementation of the proxy class, a call to the same method as the proxy class is initiated.

2) Run the profile content by reflection (this is the basic principle of the IOC container)

Student class:

 Public class Student {    publicstaticvoid  Show () {        System.out.println ("is Show () ");}    }

The configuration file takes the TXT file as an example (Pro.txt):

ClassName == Show

Test Class (Application):

Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.lang.reflect.Method;Importjava.util.Properties;/** We use the reflection and configuration file, can make: the application updates, no need to make any changes to the source code * We just need to send the new class to the client, and modify the configuration file to*/ Public classDemo { Public Static voidMain (string[] args)throwsException {//get a Class object by reflectionClass Stuclass = Class.forName (GetValue ("ClassName"));//"Student"//2 Get the Show () methodMethod m = Stuclass.getmethod (GetValue ("MethodName"));//Show//3. Call the show () methodM.invoke (Stuclass.getconstructor (). newinstance ()); }    //This method receives a key that gets the corresponding value in the configuration file     Public StaticString GetValue (String key)throwsIOException {Properties Pro=NewProperties ();//Gets the configuration file objectFileReader in =NewFileReader ("Pro.txt");//Get input streamPro.load (in);//to load a stream into a configuration file objectIn.close (); returnPro.getproperty (key);//returns the value that is obtained based on key    }}

Console output

Demand:
When we upgrade this system, do not student class, and need to write a new Student2 class, then only need to change the Pro.txt file content. The code doesn't have to be changed.

The Student2 class to replace:

The configuration file is changed to:

Console output: is Show2 ();

3) Cross-check through reflection

Generics are used at compile time, and generic erase (disappears) after compilation. So it's possible to pass reflection over a generic check.

 Packagefanxing;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;/** through reflection over generic check * * For example: There is a collection of string generics, how can I add an integer type value to this collection? */ Public classfanxing { Public Static voidMain (string[] args)throwsException {ArrayList<String> strlist =NewArraylist<>(); Strlist.add ("AAA"); Strlist.add ("BBB"); //Strlist.add (+);//If you add 100 directly here, the compilation will be an error. //gets the ArrayList class object, calling the Add () method in reverse, adding dataClass ListClass = Strlist.getclass ();//gets the byte-code object of the Strlist object//get the Add () methodMethod m = Listclass.getmethod ("Add", Object.class); //Call the Add () methodM.invoke (strlist, 100); //iterating through the collection         for(Object obj:strlist) {System.out.println (obj); }    }}

Reference:

71799078

61614873

The reflection mechanism of Java (important)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.