JAVA rich handsome technology-Reflection (1)

Source: Internet
Author: User

JAVA rich handsome technology-Reflection (1)
Preface I suddenly found that I haven't written a blog for a long time. I wrote about Android before. Today, I am eager to write a JAVA-based blog. Don't ask me why? Rich and willful! Today, let's talk about reflection mechanisms. People who have studied JAVA may not understand reflection, but they must have heard of reflection, but they have only heard of reflection. Because reflection is not used in many places, however, the use of reflection often solves the major problem of scratching our scalp. For historical issues such as why reflection is not just a normal shot, let's leave it to the historian for research... Before talking about reflection, we should first understand the concept of the next class. Class is an abstract concept. For example, "My dad is Li Gang, my dad is Li shuangjiang." From this sentence, we found that Li Gang and Li shuangjiang are two people, let's abstract their features, and we find they all look like people. Yes, so we can use people as an abstraction of them. In other words, Li Gang and Li shuangjiang are specific examples of people. Therefore, we can use a Person representative to represent this abstraction. Now that we understand the concept of classes, do we also need to abstract the classes that accompany us through day and night to prove them? That's the Class! Class is the abstraction of java classes. It abstracts java commonalities, such as Class names, Class constructor methods, Class member variables, Class fathers, and Class methods. In this case, we can use this Class to obtain information about all aspects of this Class, perhaps more detailed than checking accounts. Every Class we create, such as the person Class, is actually an instance of the Class to save the information such as the name, variable, and method of the person Class, in the memory, it indicates that the byte code of the person class is saved. If you understand this and accept my opinion, we can continue to talk about it in a common language. Since the person class has its own bytecode, can we get this bytecode? The answer is yes, and there are more than one method. Refer to the Code: copy the code public static void main (String [] args) throws Exception {// first method, directly obtain the bytecode Class cls1 = Person through the Person Class. class; // Method 2: Obtain the byte code Person = new person () of the Person Class through the instance of the class; Class cls2 = person. getClass (); // method 3: Call the static method of the Class to obtain the bytecode of the corresponding Class. This method throws the exception Class cls3 = Class. forName ("Person");} copy the code. From the code, we can conclude that the byte code of the Person Class is a specific instance of the Class. We can also guess that, as for what the class bytecode contains, I will explain it later. Let's take a look at the following code: System. out. println (cls1 = cls2); System. out. println (cls2 = cls3); when we run the program, we will find the output: truetrue, the three things are actually the same thing, so it is a good explanation: in the java virtual machine, each class is saved as a bytecode to store information about the class, such as the name, parent class, variable, and method. There is only one bytecode for a class in the virtual machine, that is, when the class is loaded for the first time, the class bytecode is loaded into the Java Virtual Machine, there are three methods to obtain the class bytecode from the Virtual Machine (PS: the third method is the most commonly used), but you don't have to worry about how to use this bytecode, we need reflection. To put it bluntly, we just want to rape this bytecode (Class )..... (~ O ~)~ ZZ understands reflection. Now that we have explained the Class, we can start to talk about reflection. What is reflection? Reflection maps various components of a class into different types. We know that a java class can be represented by a class Object, the components of this class include names, variables, constructor methods, and so on. Of course we can use java classes to represent them one by one. In other words, the Class of the java Class provides a series of methods for us to obtain information such as variables, methods, and constructor. The information is also represented by instances of corresponding classes, that is, Field, Method, Constructor, and so on. In other words, Field is the abstraction of all variables in the java class. Similarly, Method is the abstraction of all methods in the java class. If you still cannot understand it, it is normal, let's look at the code to better understand it. Constructor is the abstraction of all Constructor methods in the java class. So how can we get the class construction method through reflection? refer to the Code: copy the code public Class Test {public static void main (String [] args) throws Exception {class cls = Person. class; // get the byte code Constructor constructor1 = cls. getConstructor (); // call getConstructor () to obtain the Person construction method without parameters: Person p1 = (Person) constructor1.newInstance (); // call newInstance () constructor constructor2 = cls. getConstructor (int. class); // call getConstructor (*. class) Get Person Construction Method with parameters: Person p2 = (Person) constructor2.newInstance (1); // call newInstance (int) to execute construction method with parameters} class Person {public Person () {System. out. println ("construction method without Parameters");} public Person (int I) {System. out. println ("Construction Method with Parameters") ;}} copy the code console output: No construction method with parameters here we will start to explain, the Code passes through Person. class. getConstructor () is used to obtain the Constructor In the bytecode and put it in the constructor instance constructor. Obviously, this Constructor is not a Person constructor, but stores Pe Rson constructor is an instance of the rson constructor. Therefore, we can call newInstance () to obtain and execute the constructor's person class constructor. The constructor executes the constructor and returns an Object instance, convert it into a Person and save it in the person variable. This is the whole process of calling reflection to obtain the constructor to generate an instance. In the code, we can also know how to obtain the constructor with parameters. This is the bytecode that we need to get in getConstructor () as the parameter corresponding to the input constructor, for example, in the Code of Person (int I), we need to input an int. class (or Integet. TYPE. However, if you are greedy to obtain all the constructor methods, you can use getConstructors (): Class cls = Person. class; // get the byte code Constructor [] constructors = cls. getConstructors (); // call getConstructor () to obtain the Person construction method without parameters for (Constructor c: constructors) {// Person p = c. newInstance (***); traverses the execution constructor} and uses the for loop to process the constructor you need. We have finished the reflection of the constructor. Next we will talk about the reflection usage of the member variables. The Convention is to read the code first: copy the code public class Test {public static void main (String [] args) throws Exception {Person p = new Person ("Xiaohong", 20 ); class cls = Class. forName ("com. net168.test. person "); Field fieldName = cls. getField ("name"); // is the fieldNmae value red? Error! This variable only represents the name of the Person class and does not correspond to the object // System. out. println (fieldNmae); // fieldNmae does not represent a specific value, but only a variable. Therefore, we need to input a person instance to obtain the corresponding value System. out. println (fieldName. get (p) ;}} class Person {public Person (String name, int age) {this. name = name; this. age = age;} public String name; private int age; // for some people, age is a secret !} The replication code is similar to the reflection Implementation of the constructor. We first get the Person's bytecode cls, and then map the Person member variables into a Field class, here we will set Person. the name variable is mapped to the fieldName object. Of course, we cannot simply get our "red" from the fieldName object ", fieldName is obtained from cls rather than from the person instance, so its value is not red; instead, we can associate fieldName with the instance p of the person in Xiaohong, that is, call fieldName. get (p) can get the small red string. However, if we want to get a small red age, most women's ages are secrets. Can we also get private variables like this? Modify the following code: Person p = new Person ("Xiaohong", 20); Class cls = Class. forName ("com. net168.test. person "); Field fieldAge = cls. getField ("age"); System. out. println (fieldAge. get (p); the execution result is: Exception in thread "main" java. lang. noSuchFieldException: ageat java. lang. class. getField (Unknown Source) at com. net168.test. test. main (Test. java: 11) without this field, it is clear that this age field exists! However, we found that the girl's age was private and she refused to tell us what to do? She doesn't want to tell us, so we can't know it anymore? Silk won't be so easy to yield! So we can perform a little processing, as follows: Person p = new Person ("Xiaohong", 20); Class cls = Class. forName ("com. net168.test. person "); Field fieldAge = cls. getDeclaredField ("age"); // gets the private variable fieldAge of the class. setAccessible (true); // set this private variable to be accessible to the System outside. out. println (fieldAge. get (p); getDeclaredField () can be used to obtain the private variables of the Person class. In addition, we can use setAccessible (true) after obtaining private variables that are not visible to the outside world) set this private variable to be forcibly accessible. Brute force, JAVA reflection is also called brute force reflection by some people... When running the code, we will know the young of Xiaohong: Reflection of the 20 member methods. If you understand the reflection of the previous member variables and constructor methods, basically, it is no longer difficult to understand the reflection of Member methods. If you don't want to sell off the code, you should first move the code up and down: copy the code public class Test {public static void main (String [] args) throws Exception {Person p = new Person (); Class cls = p. getClass (); // get the byte code of Person // obtain the setName () Method. The parameter must be set to String Method method1 = cls. getMethod ("setName", String. class); method1.invoke (p, "James"); // associate p, enter "James" and execute this method // obtain the getName () method, if there is no parameter, set it to null Method meth. Od2 = cls. getMethod ("getName", null); String name = (String) method2.invoke (p, null); // The type returned by invoke is Object System. out. println (name); // obtain the static Method. Because the static Method only depends on the class, you do not need to provide the specific instance Method method3 = cls. getMethod ("show", int. class); // method3.invoke (p, 1); provide the specific instance p. You can also compile method3.invoke (null, 1) ;}} class Person {public String name; public String getName () {return name;} public void setName (String name) {this. name = Name; System. out. println ("Set name value:" + name);} public static void show (int I) {System. out. println ("this is a static method:" + I);} program running result: Set name value: James this is a static method: 1 in method reflection, we use the Method class. Because it is similar to the constructor Method, I will not explain the differences between methods with no parameters. In general, it is to get the corresponding Method of the Person class through the byte code of Person and save it to an object of Method, and then use this object to match with the specific instance of Person, with invoke (), you can call the corresponding method of a specific instance. Here, we need to pay attention to the reflection of static methods. Because static methods belong to a class and not a specific object, when we call the invoke () of static methods, you do not need to input an object. Of course, it does not matter if you want to input a specific instance. The answer is still correct.

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.