The Java reflection mechanism of Spring IOC principle

Source: Internet
Author: User

1, Reflection concept and why to use reflection

We consider a scenario in which an object would want to view its own member properties if we were running the program.

Then consider another scenario , what if we want to get the information of a class classes at runtime, such as its properties, construction methods, general methods, and then consider whether to create its object. This requires the use of reflection.

We. java files become. class files after compilation, which is like a mirror, itself. Java, in the mirror is. class, they are actually the same; so the same way, we see that the reflection of the mirror is. Class and can be compiled by Decompile , Learn about the true nature of the. java file. that is reflection .

The official concept: reflection is a feature of the Java language that allows a program to check itself at runtime (when it is not compiled) and to manipulate internal members. For example, it allows a Java class to acquire all its member variables and methods and display them.

2, get the class three ways

The first way:  
Class c1 = Class.forName (User);  
The second way:  
each type in//java has a class attribute.  
Class C2 = User.class<span style= "font-family:arial, Helvetica, Sans-serif;" >;  </span>
//Third Way:  
any Java object in the//java language has the GetClass method  
user U = new user ();  
Class C3 = U.getclass (); C3 is the Run-time class (The Run-time class of E is User)  
3. Create Object Method

Class c =class.forname ("User");  
  
Creates a new instance of the class represented by this class object,  
object o = c.newinstance ();//calls a parameterless constructor method for user.  
4. Get class Attributes

A, get all property modifiers, property names

Gets the entire class  
            C = Class.forName ("Java.lang.Integer");  
            Get all Properties
            field[] fs = C.getdeclaredfields ();  
       
            Defines a variable-length string that is used to store attributes  
            stringbuffer sb = new StringBuffer ();  
            By appending the method, each attribute is spliced into this string  
            //Outermost public definition  
            sb.append (modifier.tostring (C.getmodifiers ()) + "class" + C.getsimplename () + "{\ n");  
            Each property inside for  
            (Field field:fs) {  
                sb.append ("\ t");//Space  
                Sb.append (modifier.tostring ( Field.getmodifiers ()) + ""),//Get the modifiers for the property, such as public,static, etc.  
                sb.append (Field.gettype (). Getsimplename () + ""); The name of the type of the property  
                Sb.append (Field.getname () + "; \ n");//property's name + carriage return  
            }  
            sb.append ("}");  
<span style= "White-space:pre" >	</span>  /Output
            System.out.println (SB);  
b, get specific properties and assign values

public static void Main (string[] args) throws exception{  
              
    //Previous way:/  
    * 
    User U = new user (); 
    U.age = 12; Set 
    System.out.println (u.age);//get  
              
    //Get class  
    C = Class.forName ("User");  
    Get id attribute  
    Field idF = C.getdeclaredfield ("id");  
    Instantiate this class to assign o  
    Object o = c.newinstance ();  
    Break Encapsulation  
    idf.setaccessible (TRUE);//use reflection mechanism to break encapsulation, resulting in unsafe properties of Java objects.  
    //The id attribute of the O object is assigned to the "  
    Idf.set" (O, "a");//set  
    //get  
    System.out.println (Idf.get (o));  
5, obtain the method


Method keyword

Meaning

Getdeclaredmethods ()

Get all the methods

Getreturntype ()

Get return type of method

Getparametertypes ()

Get incoming parameter type for method

Getdeclaredmethod ("Method name", Parameter type. Class,......)

Get a specific method

Construct method Keywords

Meaning

Getdeclaredconstructors ()

Get all the construction methods

Getdeclaredconstructor (parameter type. Class,......)

Get a specific construction method

Parent class and Parent interface

Meaning

Getsuperclass ()

Gets the parent class of a class

Getinterfaces ()

Gets the interface of a class implementation


6, the role of reflection mechanism

Advantages:

A, the Java reflection mechanism is to increase the flexibility of the program, to avoid the program to write dead to the code.
For example: instantiating a person () object, without reflection, requires a new person (); If you want to become an instantiation of another class, you must modify the source code and recompile.
Using Reflection: Class.forName ("person"). newinstance (); And this class description can be written to a configuration file, such as **.xml, so if you want to instantiate other classes, just modify the configuration file's "class description". There is no need to rewrite the code and compile it. used when loading database drivers in Javaweb.
b, increase the flexibility of the program.
For example, in struts. The requested distribution control.
When the request comes. Struts through the query configuration file. Find the action method that corresponds to the request. The action is then instantiated by reflection. and invoke response method. If reflection is not applied, then you can only write dead into the code.


Reflection is generally used more in frames. Because the framework needs to be more relevant. High flexibility requirements.

Disadvantages:
Using reflection will reduce the performance of our software and increase the complexity, so we need to use it carefully.




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.