Reflection mechanism in Java and Java reflection mechanism

Source: Internet
Author: User

Reflection mechanism in Java and Java reflection mechanism

Notes for learning Java !!!

If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group with the group number 618528494.Let's learn Java together!

Reflection: At that time, I often heard them say that I have read some materials and may have used them in the design mode. But I feel that I don't have a deep understanding of it. I learned it again this time, it feels okay!

 

First, let's take a look at the concept of reflection:

It mainly refers to the ability of a program to access, detect, and modify its own state or behavior, and according to the status and results of its own behavior, adjusts or modifies the status and semantics of the behavior described by the application.

Reflection is a powerful tool in Java that allows us to easily create flexible Code. The Code can run the configuration again without the need for source code links between components. However, improper reflection is costly!

Look at the concept is dizzy, continue to look down.

 

Ii. Functions of the reflection mechanism:

1. decompilation:. class -->. java

2. Access the attributes, methods, and constructor of the java object through the reflection mechanism;

This seems easier to understand. Let's take a look at how to implement these functions.

 

Iii. Here, let's take a look at the classes in which sun provides us with reflection mechanisms:

Java. lang. Class;

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

Java. lang. reflect. Method;

Java. lang. reflect. Modifier;

 

Many operations such as methods and attributes in reflection can be queried from these four classes. Which of the following statements should we learn to constantly query APIs? That is our best teacher.

 

4. Specific functions:

1. There are three methods for obtaining the reflection mechanism class. Let's get the Employee type.

 

[Java]View plain copy print?
  1. // Method 1:
  2. Classc1 = Class. forName ("Employee ");
  3. // Method 2:
  4. // In java, each type has the class attribute.
  5. Classc2 = Employee. class;
  6. // Method 3:
  7. // Any java object in java has the getClass method.
  8. Employeee = new Employee ();
  9. Classc3 = e. getClass (); // c3 is the runtime class (e's runtime class is the Employee)

 

 

 

2. Create an object: Obtain the object of the class and use newInstance:

 

[Java]View plain copy print?
  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 parameter-free constructor of Employee.



 

3. Get attributes: All attributes and specified attributes:

A. Let's first look at how to get all the attributes:

 

[Java]View plain copy print?
  1. // Obtain the entire class
  2. Class c = Class. forName ("java. lang. Integer ");
  3. // Obtain all attributes?
  4. Field [] fs = c. getDeclaredFields ();
  5. // Defines a variable-length string for storing attributes
  6. StringBuffer sb = new StringBuffer ();
  7. // Concatenate each attribute to this string using the append method.
  8. // Public definition of the outermost side
  9. Sb. append (Modifier. toString (c. getModifiers () + "class" + c. getSimpleName () + "{\ n ");
  10. // Each attribute in it
  11. For (Field field: fs ){
  12. Sb. append ("\ t"); // Space
  13. Sb. append (Modifier. toString (field. getModifiers () + ""); // get attribute modifiers, such as public and static.
  14. Sb. append (field. getType (). getSimpleName () + ""); // name of the attribute type
  15. Sb. append (field. getName () + "; \ n"); // attribute name + press ENTER
  16. }
  17. Sb. append ("}");
  18. System. out. println (sb );


B. Get specific attributes and learn from the traditional methods:

 

 

 

[Java]View plain copy print?
  1. Public static void main (String [] args) throws Exception {
  2. <Span style = "white-space: pre"> </span> // previous method:
  3. /*
  4. User u = new User ();
  5. U. age = 12; // set
  6. System. out. println (u. age); // get
  7. */
  8. // Obtain the class
  9. Class c = Class. forName ("User ");
  10. // Obtain the id attribute
  11. Field idF = c. getDeclaredField ("id ");
  12. // Instantiate this class to o
  13. Object o = c. newInstance ();
  14. // Break the Encapsulation
  15. IdF. setAccessible (true); // The reflection mechanism can be used to break the encapsulation, leading to insecure attributes of java objects.
  16. // Assign "110" to the id attribute of the o object"
  17. IdF. set (o, "110"); // set
  18. // Get
  19. System. out. println (idF. get (o ));
  20. }


 

4. Get methods and constructor methods. I will not describe them in detail. Just look at the keywords:
 
 

Method keywords

Description

GetDeclaredMethods ()

Get all methods

GetReturnType ()

Obtain the method replacement type

GetParameterTypes ()

Obtain the input parameter type of the method.

GetDeclaredMethod ("method name", parameter type. class ,......)

Obtain a specific method

 

 

Constructor keywords

Description

GetDeclaredConstructors ()

Obtain all constructor Methods

GetDeclaredConstructor (parameter type. class ,......)

Obtain a specific Constructor

 

 

Parent class and parent interface

Description

GetSuperclass ()

Obtain a class of parent class

GetInterfaces ()

Obtain an implemented Interface

In this way, we can obtain various contents of the class and decompile them. For JAVA, a language that requires compilation and execution, the reflection mechanism can make the code more flexible and easier to implement object-oriented.

 

 

5. Reflection and configuration files make our programs more flexible:

During the design model learning, reflection was used to read database link strings more easily when learning abstract factories. At that time, I did not understand it too well and copied it. Let's take a look at the use of reflection + configuration files in. NET:

The configuration file used at that time is the app. config file in XML format. Enter the content of the Linked database in it:

 

[Html]View plain copy print?
  1. <Configuration>
  2. Lt; deleetask>
  3. <Add key = "" value = ""/>
  4. Lt;/appSettings>
  5. </Configuration>


 

Reflection statement:

 

[Csharp]View plain copy print?
  1. Assembly. load ("current assembly name"). CreateInstance ("Current namespace name". Name of the class to be instantiated );


 

 

The advantage is that we can easily change the database. For example, if we upgrade the system database from SQL Server to Oracle, We will write two copies of layer D, you can change the content of the configuration file, or select the configuration file by adding conditions, which makes it very convenient.

Of course, the same is true in JAVA, except that the configuration file is. properties, which is called an attribute file. Read the content through reflection. In this way, the code is fixed, but the content of the configuration file can be changed, which makes our code much more flexible!

 

In summary, the re-learning and flexible use of JAVA reflection can make our code more flexible, but it also has its shortcomings, it will reduce the performance and complexity of our software, so we need to use it with caution.

Notes for learning Java !!!

If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group with the group number 618528494.Let's learn Java together!

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.