The cake-rich technique in Java--reflection (I.)

Source: Internet
Author: User

Objective

Suddenly found a long time not to write a blog, the front is written about Android, today suddenly there is an impulse to write a blog based on Java technology, don't ask me why? Rich, capricious!

Let's talk about the reflection mechanism today. People who have studied Java do not necessarily know how to reflect, but they have heard of reflection, but they have only heard it, because there is not so much reflection, but the good of reflection often solves the big problem of scratching our scalp. As for the historical problems such as why it is called reflection, rather than a forward shot, it is left to historians to study it ...

The cornerstone of Reflection

Before we talk about reflection, we should first understand the concepts of the following classes to introduce. Class is an abstract concept, for example "My father is Li gang my father Li Shuangjiang", from this sentence we found that there are Li Gang, Li Shuangjiang These two people, we come to abstract their characteristics, we find them are like people. Yes, then we can take people as an abstraction, and in turn Li Gang and Li Shuangjiang are a concrete example of human beings, so we can represent this abstraction with a person class representing people. Now that we understand the concept of class, the Java classes that spend the day and night with us, should we also abstract a class to prove them, yes, that's class!

Class is the abstraction of Java class, which abstracts out the generality of Java, such as the name of the class, the method of constructing the class, the member variables of the class, the father of the class, the method of the class, etc. In that case, we can get information about every aspect of this class, and perhaps more detailed than checking the account. Every class we create, such as the person class, in the end, we instantiate a class instance to hold the name, variable, and method of the person class, which in memory is the byte code that holds the person class, and if you understand that and accept my opinion, So we have a common language that we can go on.

Now that the person class has its own bytecode, can we get to this byte code? The answer is yes, and there's more than one way. See Code:

public static void Main (string[] args) throws Exception {///first method, directly through the person class to get the byte code class CLS1 = Person.class;  The second method, through an instance of the class, gets the byte code of the person class person person = new person ();  Class cls2 = Person.getclass (); The third method, called the class class static method to get the corresponding class bytecode, the method throws an exception class CLS3 = Class.forName ("person");}

From the code, we can conclude that the byte code of the person class is the specific instance of class, and we can guess that the byte code of the class contains something, so let's guess, I'll explain it later. Let's take a look at the following code:

System.out.println (cls1 = = CLS2); System.out.println (cls2 = = CLS3);

We run the program and we see the output:

True
True

These three things are the same thing, then it is very good to explain: In the Java Virtual machine, each class will be saved as a byte code, to hold the information of the class such as name, parent class, variables, methods and so on. A class of bytecode in a virtual machine and only one, that is, the first time the class loaded the class's bytecode loaded into the Java virtual machine, and there are three ways to get the class's bytecode from the virtual machine (PS: The third method is most commonly used), but you do not doubt to get this bytecode for what to do with, We're going to reflect, we're just going to rape this bytecode (Class) ..... (~ o ~) ~zz

Understanding Reflection

Now that we've explained the class, we can start to talk about reflection. What is reflection? Reflection is to map the various components of the class into various classes, we know that a Java class can be represented by a class object, the composition of this class has names, variables, construction methods and other information, we can certainly use a Java class representation. In other words, the class class that represents the Java class provides a series of methods that give us information about the variables, methods, construction methods, and so on, which are represented by instances of the corresponding classes, that is, field, method, constructor, and so on. Or more generally, field is the abstraction of all the variables in the Java class, and the same method is the abstraction of all the methods in the Java class, if it is still not understood, it is normal to look down on the code to understand better.

Reflection of the construction method

As we know from the previous, constructor is the abstraction of all the constructor methods of the Java class. So how do we get the constructor of the class by reflection, see Code:

public class test{public        static void Main (string[] args) throws Exception {                class CLS = person.class;//Gets the Bytecode                Constructor constructor1 = Cls.getconstructor ();//Call GetConstructor () gets the person without a parameter constructor method person        p1 = (person) Constructor1.newinstance ();//By calling Newinstance () to perform an parameterless construction method                Constructor Constructor2 = Cls.getconstructor ( Int.class);//Call GetConstructor (*.class) to get the person with the parameter construction method person        p2 = (person) constructor2.newinstance (1);//    the}}class person{public Person        () {System.out.println ("parameterless constructor method") is executed by calling newinstance (int) to execute the parameter construction method;}    public person (int i) {System.out.println ("with parameter constructor method");}}

Console output:

Non-parametric construction method
Construction method with parameters

Here we begin to explain that the code obtains the bytecode of the person class by person.class and saves it in an instance of the class class CLS, and then through Cls.getconstructor () To get the construction method in the bytecode and put it into the constructor instance constructor, it is clear that this constructor is not a person's construction method, but rather to save an instance of the person constructor method, So we can call newinstance () to get the constructor of the person class saved in constructor and execute, construct the method to execute and return an instance of object, and convert it to person and save it in the person's variable. This is the whole process of invoking reflection to get the constructed method to build the instance.

In the code, we can also know how to get the constructor of the parameter, which we need in GetConstructor () is passed the constructor method corresponding to the parameter of the bytecode, such as code in the person (int i) We need to pass in a int.class (or Integet.type) byte code to provide the constructor method that the class locates need to get. But if you're greedy and want to get the whole construction method, no problem, through GetConstructors ():

Class CLS = person.class;//Gets the byte code of the person class constructor[] constructors = cls.getconstructors ();//Call GetConstructor () Gets the person parameterless constructor method for (Constructor c:constructors) {//person p = c.newinstance (* * *); Traversal execution Constructor Method}

Then, with a for loop, you can handle the construction method you need.

Reflection of member variables

Now that we're done with the reflection of the construction method, we'll turn to the reflection of the member variable. It's customary to look at the code first:

public class test{public        static void Main (string[] args) throws Exception {person                p = new Person ("Little Red");                Class cls = Class.forName ("Com.net168.test.Person");        Field fieldName = Cls.getfield ("name");        is the value of Fieldnmae a little red? Wrong! It is only the variable that represents the name of the person class, and does not correspond to the object body//        System.out.println (fieldnmae);         Fieldnmae does not represent a specific value, it represents only one variable, so we need to pass in a person instance to get to its 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! }

Similar to the implementation of the reflection of the construction method, we also first map the person's member variable into a field class by acquiring the bytecode CLS of the person. Here we will person.name this variable map to fieldname This object, of course, we can not simply from fieldname this object to get our "Little Red", Because FieldName is obtained from the CLS and not from the instance of person, it is not a small red, but we can associate with the FieldName by the instance p of the person of Little Red, which is called Fieldname.get (p) To get the little red string.

But if we want to get a little red age, women's age is mostly secret, private variables can we also get it? Modify the following code:

Person p = new person ("Little Red", 20); Class cls = Class.forName ("Com.net168.test.Person"); Field fieldage = Cls.getfield ("Age"); System.out.println (Fieldage.get (p));

The execution results are:

Exception in thread "main" java.lang.NoSuchFieldException:age
At Java.lang.Class.getField (Unknown Source)
At Com.net168.test.Test.main (test.java:11)

Without this field, obviously there is this age field! But we found that the old girl's age is private, she just won't tell us ah, how to do? She didn't want to tell us, so we wouldn't know? Dick Silk is not so easy to yield! So we can do a little bit, as follows:

Person p = new person ("Little Red", 20); Class cls = Class.forName ("Com.net168.test.Person"); Field fieldage = Cls.getdeclaredfield ("Age");//Gets the private variable fieldage.setaccessible (true) of the class;// Setting this private variable can be accessed outside the SYSTEM.OUT.PRINTLN (Fieldage.get (p));

The private variables of the person class can be obtained through Getdeclaredfield (), and we can also set the private variable to be forced access by setaccessible (true) after acquiring a private variable that cannot be seen by the outside world. Violence, the reflection of Java is also called violent reflex by some people ... Run the code, we'll know the red Christina: 20

Reflection of Member methods

If you understand the previous member variables and the reflection of the construction method, it is not difficult to understand the reflection of the member method basically, not suspense, or first up and down the code:

public class test{public static void Main (string[] args) throws Exception {person p = new person (); Class cls = P.getclass ();//Get the bytecode of person//Get SetName () method, need to pass in parameter as String method method1 = Cls.getmethod ("Setn        Ame ", String.class); Method1.invoke (P, "xiaoming");//correlate P, enter "Xiaoming" and execute the method//Get the GetName () method, and the parameterless is set to null method METHOD2 = Cls.getmethod ("GetName        ", null);        String name = (string) method2.invoke (p, NULL);//invoke returns a type of object System.out.println (name); Gets the static method, since the static method relies only on the class, so there is no need to provide a concrete instance of method method3 = Cls.getmethod ("show", int.class);//Method3.invoke (P, 1);            A specific instance of P can also be compiled by 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 is:" + name);    } public static void show (int i) {System.out.println ("This is a static method:" + i); }}

Program Run Result:

Set the name value to: xiaoming
Xiao ming
This is a static method: 1

In the reflection of the method, we are using this class of methods, because it is similar to the construction method, so I do not have to get the method of the participation of the different ways to explain. In general, it is through the person's bytecode to obtain the corresponding method in the person class and save it to an object of method, and then through the object with a specific instance of person, through invoke () can invoke to the specific instance of the corresponding method. Here we need to pay attention to the reflection of the static method, because the static method belongs to a class does not belong to a particular object, so we call the static method of Invoke (), do not need to pass in an object, of course, you have to pass in a specific instance is not related, the answer is still correct.

So much for reflection, there is time to talk about the deep application of reflection and the usefulness of reflection in framing. It's a waste of my night playing. Self-willed Ah ...

Enjoy wind chimes
Source: http://www.cnblogs.com/net168/
This article is copyright to the author and the blog Park is shared, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location to the original connection, or next time not to you reproduced

The cake-rich technique in Java--reflection (I.)

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.