Dark Horse programmer [reflection mechanism in java], dark horse java

Source: Internet
Author: User

Dark Horse programmer [reflection mechanism in java], dark horse java

Reflection mechanism in Java

------- Android training, java training, and hope to communicate with you! ----------

The reflection mechanism of java is one of the features of java. The reflection mechanism is the basis for building the framework technology. Using Reflection can make the program more flexible and avoid writing the program into the code. Compared with many beginners who have only been familiar with java basics, reflection is still a very obscure concept. Let's take a look at some applications of reflection.

The java reflection mechanism is used to dynamically obtain information and call object methods in the running state. Java reflection has three dynamic properties: 1. generate an object instance during runtime, 2. Call and issue during runtime, and 3. Change attributes during runtime.

So what is the reflection principle? First, let's take a look at the java program execution process. To run a java program, the java class must be loaded by the java Virtual Machine. All the running programs have loaded the required classes at compilation. I have to mention it here. I believe many people do not have a clear concept about what is compile and what is run, during compilation, the compiler helps you translate the code into codes that can be recognized by devices. That is to say, the compiler will do some simple work during compilation, such as checking whether your syntax is correct, there are no errors in keyword or name writing and loading classes. This is all the work to be done during compilation. What is done during runtime? The runtime is the runtime when your program starts and the code is loaded into the memory. The runtime check is the operation and judgment in your memory, here is a small example:

   int[] nums = new int[3];        nums[4] = 12;

Obviously, the code above will see an array subscript out-of-bounds error, but the program does not report an error during compilation, but will only report an ArrayIndexOutOfBoundsException error at runtime, this is the difference between compile time and runtime.

The reflection mechanism of java is not sure which class is loaded during compilation. It is loaded and used only when the program is running, let's look at the reflection Execution Process in a simple figure:

The Java reflection mechanism can understand the basic structure of the class, and the ability to explore the java class structure becomes "self-audit ", for example, the automatic prompt function when we use eclipse software to write code is the principle of java reflection. So what functions can we implement through java reflection? 1. determine the class of any object at runtime. construct any class object at runtime. determine the attributes and methods of any class at runtime. 4. call the methods of any object at runtime. Common classes for java reflection include Class: the Core Class of reflection. The Class can be used to obtain Class attributes, methods, and other content. Filed class: indicates the attribute of the class. You can obtain and set the attribute values in the class. Method class: indicates the Method of a class. It can be used to obtain information about methods in the class or to execute methods. Constructor class: Constructor class.

Well, we have learned some basic information about java reflection. Next we will implement the reflection functions one by one using code:

First, it is also the simplest one. First, we need to use the Class. The Class must be made out of instances first. But the Class has no constructor. How should we instantiate it, there are three methods to create a Class:

Public static void main (String [] args) {// first method, using the object. getClass () method User user User = new User (); Class <? Extends User> cs = user. getClass (); System. out. println (cs); // method 2, by class name. class Class <User> cs1 = User. class; System. out. println (cs1); // The third method, through the forName () method of the Class itself, note that the forName () method will throw the same, and the parameters in the package must contain the complete package name and Class name <?> Cs2 = null; try {cs2 = Class. forName ("cn. fanfu. demo. user ");} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} System. out. println (cs2 );}

Among them, the third forName () method can instantiate the Class without Class uncertainty, which is more flexible.

The second is to construct a new instance for creating Class objects through the Class parameters:

Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, expiration, InstantiationException, IllegalAccessException, InvocationTargetException {// For more intuitive display, use the String Class directly <?> Cs = Class. forName ("java. lang. String"); char [] ch = {'da', 'home', 'ha ','! ','! '}; // Call the Class Constructor with parameters. The value in the function is class. Class Constructor <?> Cst = cs. getConstructor (char []. class); String name = (String) cst. newInstance (ch); System. out. println (name); // because of the exception, the Code is not visually displayed, So I directly threw it to the Virtual Machine}

The third is to obtain a series of elements such as the class structure, interface, method, and attribute:

Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, expiration, InstantiationException, IllegalAccessException, InvocationTargetException {// create two classes first <?> Cs = Class. forName ("cn. fanfu. demo. User"); Constructor <?> [] Con = null; // return a Constructor [] Array Using the getConstructors () method. Each Constructor of this class is stored in the array. con = cs. getConstructors (); for (Constructor <?> Item: con) {System. out. println (item) ;}// return a Class using the getInterfaces () method <?> [] Array. Each interface Class of this Class is stored in the array. <?> [] Inter = cs. getInterfaces (); for (Class <?> Item: inter) {System. out. println (item) ;}// return a Class using the getSuperclass () method <?> Class <?> Parent = cs. getSuperclass (); // java only supports single inheritance, so there is only one parent class System. out. println (parent); // return a Method [] array through the getMethods () Method. The method [] Method = cs is stored in the array. getMethods (); for (Method item: method) {System. out. println (item);} // returns a Field [] Array Using the getDeclaredFields () method. Each attribute Field [] fiel = cs is stored in the array. getDeclaredFields (); for (Field item: fiel) {System. out. println (item);} // The getDeclaredFields () method can obtain all attributes. The getFields () method can only obtain the public attribute Field [] fiel1 = cs. getFields (); for (Field item: fiel1) {System. out. println (item );}}

The fourth is to get or modify the attribute value of the class:

Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, exception, InstantiationException, exception, InvocationTargetException, NoSuchFieldException {// create User Object User us = new User (); us. setAge (12); us. setName ("Zhang San"); Class <?> Cs = us. getClass (); // obtain the Private Attribute Value Field fl = cs. getDeclaredField ("name"); // you must first set to allow access to fl. setAccessible (true); // use the get method to specify the object to obtain the String name = (String) fl. get (us); System. out. println (name); // specify the object through the set method and modify the value fl. set (us, "Li Si"); String name2 = (String) fl. get (us); System. out. println (name2 );}

The fifth is to call the method through reflection:

Public static void main (String [] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, exception, InstantiationException, exception, InvocationTargetException, NoSuchFieldException {// create User Object User us = new User (); us. setAge (12); us. setName ("Zhang San"); Class <?> Cs = us. getClass (); // use the getMethod () Method to obtain methods in the class. This Method has two parameters: one specified Method name and the other specified Method parameter type, Method mm = cs. getMethod ("say"); // call a method through the invoke () method. This method has two parameters: one specified object and the other passed the parameter mm. invoke (us );}

Well, there are so many reflection introductions. Other columns, such as the array set, are some flexible usage, so we will not introduce them more.

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.