Reflection mechanism in Java

Source: Internet
Author: User
Digress:

The World Cup will start next weekend. For authentic fans, this is undoubtedly a long-awaited holiday, both physically and psychologically, I am fully prepared to devote myself to this four-year holiday. I wish all the fans and friends a happy holiday and enjoy it!

What is reflection mechanism?

Just like reflection in physics, we can see ourselves in front of the mirror. However, the reflection mechanism here is different from the physical reflection mechanism, which emphasizes "dynamic ". Reflection mechanisms refer to the ability of a program to access, detect, and modify its own state or behavior when the class (itself) runs. This mechanism was introduced during the design, so that the Java language has certain dynamic capabilities (the so-called dynamic capability means that the Java language cannot run as Python or Ruby does, it is allowed to change the program structure and variable type, but it can detect its own status and behavior while the program is running, and modify the field value ). Because of the existence of the reflection mechanism, the Java language is different from the hard-coded C and C ++. It is also the advantage of this mechanism, microsoft later imitated the Java language and invented the C # language, which also had this advantage.

How to implement:

All objects in Java are inherited from a basic object class object. This object is not manually written by the program. It is automatically generated by JVM when every class is used. This class provides several reflection APIs. We can call these reflection APIs to check the class-related methods, variables, names, interfaces, and inheritance ............ Related information. The reflection API provided by Sun is used to check all kinds of class information, such as reflection (the example I wrote below is to do this, every day, the JVM is working. At any time, the JVM will call the reflection API to obtain its methods, attributes, and variables as long as a class is generated and operated. List several common APIs: getname () to get the class/interface name; getdeclaredmethods () to get the method; getdeclaredfields () to get the variable .......

Example (three examples: Obtain the field, method, and name ):

The following are three examples of using the reflection mechanism: getting the name, method, attributes, and modifying attributes.

Example 1:

/* Get the method name */

Class C = NULL;

C = Class. forname (ARGs [0]);

Package P;

P = C. getpackage ();

If (P! = NULL)

System. Out. println ("package" + P. getname () + ";");

Result (example ):

Package java. util;

This example is taken from Hou Jie The instructor's book "Java reflection mechanism" section "Java reflection API operation example", as we often ask, we have written a method in EJB or introduced a package, how does the client know which package it is and which method it is? Just like above, JVM actually does the above Code on the back, and then prints the above result, that is to say, the JVM knows the information he wants to know through reflection. Now, the JVM obtains this information. At the beginning, when I learned reflection, I had a question in my mind for a long time. "reflection can only be dynamic when I look at my methods, functions, and variables, I can't operate like a dynamic language. What is the significance of this? I don't seem to find any benefits. "Here, I understand that reflection is not for you, it is for the JVM. Let the JVM or container (such as EJB) know what method and class to be obtained.

Example 2:

/* Get all methods */

Package SRC;

 

Import java. Lang. Reflect .*;

 

Public class reflectiontest {

 

Public static void main (string ARGs []) {

Try {

 

Class C = Class. forname ("Java. Lang. String"); // converts it to a Class Object object, which can be reflected.

Method M [] = C. getdeclaredmethods ();

System. Out. println (M [0]. tostring ());

/***** View all your methods ******/

For (INT I = 0; I <M. length; I ++)

System. Out. println (M [I]. tostring ());

/****************************/

 

 

/***** View your first method ****/

System. Out. println (M [0]. tostring ());

/****************************/

}

Catch (throwable e ){

System. Err. println (E );

}

 

}

}

Because Java is completely interface object programming, in Java, string and INT types, these constant types are also object-oriented. we can treat them as an object and operate them. The result obtained through the above example is the public methods of all strings.

Example 3:

/* Get and modify attributes, that is, the set and get methods we often use */

Public class test {

Public double D;

Public static void main (string ARGs [])

{

Class C = Class. forname ("test ");

Field F = C. getfield ("D"); // specify the field name struct

Test OBJ = new test ();

System. Out. println ("d =" + (double) F. Get (OBJ ));

F. Set (OBJ, 12.34 );

System. Out. println ("d =" + obj. D );

}

}

This example is taken from Hou Jie The second penultimate section of the book "Java reflection mechanism" is "fields Content Changes During the runtime". This method is much more widely used. In fact, it also contains the reflection mechanism principle, even if we use real names to convert the objects we want to operate into Class Object Class C = Class. forname ("test. the getfield () method (this method is the embodiment of the reflection system) can obtain its own variables dynamically (the so-called Dynamics here refer to when the program is running), and modify and set the variables.

What are the advantages of using reflection:

In fact, JNDI is a specific manifestation of reflection. For example, we put a class in EJB. How does the client know the method of the class we want to use? We know that the JNDI is used. In fact, JNDI is a specific manifestation of the reflection mechanism, class C = Class. forname ("Java. lang. string "); the name of the called function or method is in the dual-tone number. We can find the method to call through the name. This is what we call JNDI, JVM instantiated a class object internally. As we mentioned above, there are many methods in this class object. Through these methods, we can see all the public methods of the class he got, and call the corresponding method. Otherwise, the client cannot know what class we are calling.

Similarly, we often use the getxxx () and setxxx () methods.

It can be summarized as follows: "dynamically select the execution methods and variables, instead of writing them statically ."

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.