View of the Java reflection mechanism

Source: Internet
Author: User

reflection, at that time often listen to them, they have seen some information, but also may be used in design mode, but it does not feel a more in-depth understanding, this time to re-learn a bit, feel OK!

first, take a look at the concept of reflection:

It is the ability of a program to access, detect and modify its own state or behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.

Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled again at runtime without the need for source code linking between components. But the use of reflection is expensive!

look at the concept is very faint, continue to look down.

Two, the effect of reflection mechanism:

1, decompile:. Class-->.java

2, through the reflection mechanism to access the Java object Properties, methods, construction methods, etc.;

this seems to be easier to understand, and below we look at how to implement these features.

Three, let's take a look at Sun . The classes in the reflection mechanism are provided for us:

Java.lang.Class;

Java.lang.reflect.Constructor; Java.lang.reflect.Field;

Java.lang.reflect.Method;

Java.lang.reflect.Modifier;

Many of the methods in reflection, attributes, and so on, we can query from these four classes. Or what sentence to learn the constant query API, that is our best teacher.

Four, the specific function realization:

1, the reflection mechanism gets the class there are three ways to get the Employee type

[Java]View PlainCopy print?
    1. The first way:
    2. CLASSC1 = Class.forName ("Employee");
    3. The second way:
    4. Each type in Java has a class attribute.
    5. CLASSC2 = Employee.  class;
    6. The Third Way:
    7. Any Java object in the Java language has a GetClass method
    8. employeee = new Employee ();
    9. CLASSC3 = E.getclass (); //C3 is the runtime class (the run-time class for E is employee)

2, create object: Get the class later we'll create its object, using the newInstance:

[Java]View PlainCopyprint?
    1. Class c =class.forname ("Employee");
    2. Create a new instance of the class represented by this class object
    3. Objecto = C.newinstance ();  //Call the No-parameter construction method for employee.



3, Gets the attribute: is divided into all attributes and the specified properties:

A, let's look at the notation for all the attributes:

[Java]View PlainCopyprint?
  1. Get the entire class
  2. Class C = class.forname ("Java.lang.Integer");
  3. //Get all the properties?
  4. field[] fs = C.getdeclaredfields ();
  5. //define variable-length strings to store properties
  6. StringBuffer sb = new StringBuffer ();
  7. //Stitch each property into this string by appending the method
  8. //Outermost public definition
  9. Sb.append (Modifier.tostring (C.getmodifiers ()) + "class" + c.getsimplename () +"{\ n");
  10. //each property inside
  11. For (Field field:fs) {
  12. Sb.append ("\ t"); Space
  13. Sb.append (Modifier.tostring (Field.getmodifiers ()) +""); Gets the modifier for the property, such as Public,static, and so on
  14. Sb.append (Field.gettype (). Getsimplename () + ""); The name of the type of the property
  15. Sb.append (Field.getname () +"; \ n"); Name of property + carriage return
  16. }
  17. Sb.append ("}");
  18. System.out.println (SB);


b, get specific attributes and compare the traditional methods to learn:

[Java]View PlainCopyprint?
  1. Public static void Main (string[] args) throws exception{
  2. <span style="White-space:pre" > </span>//Previous way:
  3. /* 
  4. User U = new user ();
  5. U.age = 12; Set
  6. System.out.println (U.age); Get
  7. */
  8. //Get class
  9. Class C = class.forname ("User");
  10. //Get id attribute
  11. Field IdF = C.getdeclaredfield ("id");
  12. //Instantiate this class to assign O
  13. Object o = c.newinstance ();
  14. //Break Package
  15. Idf.setaccessible (true);  //Using the reflection mechanism can break the encapsulation and cause the properties of the Java object to be unsafe.
  16. //Assign the id attribute of the O object to "Max"
  17. Idf.set (O, "110"); //set
  18. //get
  19. System.out.println (Idf.get (o));
  20. }


4, get the method, and the construction method, no longer described in detail, just look at the keyword:

Method keyword

Meaning

Getdeclaredmethods()

Get all the methods

Getreturntype()

Get the return type of the method

Getparametertypes()

Get the incoming parameter type for a method

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

Get a specific approach

Constructor method keyword

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

Get an interface for a class implementation

This allows us to get the various contents of the class and decompile it. For JAVA , which compiles and then runs the language, the reflection mechanism can make the code more flexible and easier to implement object-oriented.

Five, Reflection plus config file, make our program more flexible:

in the design mode of learning, learning the abstract factory when the reflection to more convenient reading database link string, etc., was not too understanding, then copied. Take a look at the use of reflection + configuration files in . NET:

the configuration file used at that time is the app. config file, which is in XML format and fills in the contents of the linked database :

[HTML]View PlainCopyprint?
    1. <configuration>
    2. Lt;appsettings>
    3. <add key= "" value= " "/>
    4. Lt;/appsettings>
    5. </configuration>


The notation of reflection:

[CSharp]View PlainCopyprint?
    1. Assembly.Load ("Name of the current Assembly").  CreateInstance ("Current namespace name"). The class name to instantiate);


The advantage is that it is easy for us to change the database, for example, we upgrade the system database from SQL Server to Oracle, then we write two copies of the D layer, change the contents of the configuration file, Or add the conditions to choose a bit, bring a lot of convenience.

Of course,the same is true in JAVA, except that the configuration file here is . Properties, called a properties file. Reads the contents of the inside through reflection. This code is fixed, but the contents of the configuration file we can change, so that our code a lot of flexibility!

In summary, theJAVA reflection of the re-learning, flexible use of it, can make our code more flexible, but it also has its shortcomings, is to use it will make our software performance is reduced, complexity increases, so we also need to use it carefully.

View of the Java reflection mechanism

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.