(Dark horse programmer-diary 7) reflection and Introspection-go to the next level

Source: Internet
Author: User

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

Finally, it seems that we are about to break away from the most ignorant stage. After learning the video from instructor Zhang, I found that Java still has these profound knowledge, such as reflection and introspection. I used an object-oriented perspective to look at the class files on the hard disk. They were also objects, it can also be described. Java is so powerful. Study hard and take it to the next level.

Reflection

Class
The class represents a Java class. Its instance objects correspond to the bytecode of each class in the memory, such as the bytecode of the person class and the bytecode of the arraylist class.
A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, so their content in the memory is different. The space can be represented by objects respectively. These objects obviously have the same type. What is this type?

There are three methods in reflection to get the Instance Object (class type) corresponding to each bytecode)
1. Class Name. class, for example, system. Class // The required class has been loaded into the memory
2. Object. getclass (), for example, new date (). getclass () // instance object with a class required
3. class. forname ("Class Name"), for example, class. forname ("Java. util. date "); // a commonly used method. It is equivalent to loading the class into the memory and then obtaining the bytecode.

It indicates that the class of the Java class obviously needs to provide a series of methods to obtain information such as variables, methods, constructor, modifier, and package, the information is represented by the instance objects of the corresponding class, such as field, method, contructor, and package.

Reflection: Reflection maps various components in Java classes into corresponding Java classes. // If you are a senior, the summary is better.

Constructor class:

The constructor class represents a constructor in a class.

Obtain all the constructor methods of a class:
Example: constructor [] constructors = Class. forname ("Java. Lang. String"). getconstructors ();
Obtain a constructor:
Example: constructor = Class. forname ("Java. Lang. String"). getconstructor (stringbuffer. Class); // type used to obtain the Method
Create an instance object:
Common method: String STR = new string (New stringbuffer ("ABC "));
Reflection Method: String STR = (string) constructor. newinstance (New stringbuffer ("ABC"); // the same type of instance object must be used to call the obtained method.

Class. newinstance () method:
Example: String OBJ = (string) class. forname ("Java. Lang. String"). newinstance ();
This method first obtains the default constructor, and then creates an Instance Object using this constructor. This is not a common method, because many classes do not have the constructor of null parameters, therefore, it is best to first obtain a class constructor and then create an Instance Object Based on newinstance () in the constructor.

Field class:

The field class represents a member variable in a class.
Obtains a field in a class based on an instance object.
Field field = obj. getclass (). getfield ("X"); // X indicates the field name,

If field X is private, use the following method to obtain the field
Field field = obj. getclass (). getdeclaredfield ("X ");
Field. setaccessible (true );
Field. Get (OBJ); // used to obtain the value of the X field on an object

Changes the value of a member variable in an instance object of a class.
Class {
...
String STR = "ABC ";
...
}

Class B
{
A obj = new ();
Field field = obj. getclass (). getfield ("str"); // obtain the member variable based on the field name.
String oldvalue = (string) field. Get (OBJ); // obtain the value of the member variable
String new value = oldvalue. Replace ('B', 'A ');
Field. Set (OBJ, newvalue); // you must replace the value of the member variable on an object with a new value.
}

 

Method class:

The method class represents a member method in a class.
Obtain a method in the class:
Example:
Method charat = Class. forname ("Java. Lang. String"). getmethod ("charat", Int. Class );
Call method:
Common method: system. Out. println (Str. charat (1 ));
Reflection Method: system. Out. println (charat. Invoke (STR, 1); // call the reflected method through the invoke method in the method class
Note: If the first parameter of the invoke () method passed to the method object is null, the method object corresponds to a static method.

Execute the main method in a Class Using Reflection:
Mainmethod. Invoke (null, new object [] {New String [] {"XXX "}});
Mainmethod. Invoke (null, (object) New String [] {"XXX "});,
Note: The compiler will perform special processing. When compiling, the parameters are not treated as arrays, so the arrays will not be split into several parameters.

Array reflection:

1. Arrays with the same dimension and element types belong to the same type, that is, they share the same class instance object.

Sample Code:
Int [] a1 = new int [2];
Int [] a2 = new int [4];
A1.getclass () = a2.getclass (); // true

2. The parent class returned by the getsuperclass () method of the class instance object of the array is the class corresponding to the object class.
3. Basic Types of one-dimensional arrays can be used as objects and cannot be used as objects []. Non-basic types of one-dimensional arrays can be used as objects, it can also be used as the object [] type.
Personal Understanding: int [] can be considered as an object,
Object obj1 = A1; // Yes
Object [] obj2 = A1; // No. It can be understood that an object container and an object are assigned an equal sign.
Note: print the result returned by the arrays. aslist (A1); method, which is a hash code.

Inner province (JavaBean)

Javabean is a special Java class that is mainly used to transmit data information. The methods in this Java class are mainly used to access private fields and the method name complies with certain naming rules.
It can be understood that the class with the set and get methods is regarded as a JavaBean, because the set or get method must be used to access private fields.

In short: When a class is used as a JavaBean, the attributes of the JavaBean are inferred based on the method name. It does not see the member variables inside the Java class.
Below is a simple JavaBean
Class person {
Private string name;
Private int age;

Public void setname (string name ){
This. Name = Name;
}
Public void setage (INT age ){
This. Age = age;
}
Public String getname (){
Return name;
}
Public int getage (){
Return age;
}

}

Simple intranet operations on JavaBean

Class
{
Private int X;
Private int y;
...
Set...
Get...
...
}

Class B
{
A obj = new A (); // create the Instance Object of the class for internal operation

String propertyname = "X"; // The property name can be inferred based on the get and set methods.
Propertydescriptor Pd = new propertydescriptor (propertyname, obj. getclass (); // get the attribute description based on the attribute name.
Method methodgetx = Pd. getreadmethod (); // reflect the method in JavaBean by describing the method on the object using the property
Object retval = methodgetx. Invoke (OBJ); // CALL THE METHOD

Method methodsetx = Pd. getwritemethod ();
Methodsetx. Invoke (OBJ, 3 );

...
/*
The following is a complex introspection operation on JavaBean. First, a set of attribute descriptions is obtained.
Beaninfo = introspector. getbeaninfo (obj. getclass (); // obtain the JavaBean information by using the static method of introspector of the province class.
Propertydescriptor [] PPS = beaninfo. getpropertydescriptors (); // obtain all attribute descriptions on the JavaBean
For (propertydescriptor PD: PPS) // traverses the attribute description to determine the required and operate
{
If (PD. getname (). Equals (propertyname ))
{
Method methodgetx = Pd. getreadmethod ();
Object retval = methodgetx. Invoke (OBJ );
Break;
}
}
*/
}

 

Beanutils Toolkit
You can use the beanutils toolkit to simplify operations on JavaBean.
First load two jar, commons-beanutils.jar and common-logging-1.1.jar
Beanutils. setproperty (OBJ, "X", "9"); // If 9 of this string is passed to X of the original class, beanutils will automatically convert the type to 9 of the int type.

 

JavaBean has an attribute: private date birthday; you can perform the following operations:

Beanutils. setproperty (OBJ, "birthday. Time", "100"); // There Is A settime () method in the date class. This beanutils can perform the concatenation operation on the property.

 

Another attribute setting operation in beanutils
Propertyutils. setproperty (OBJ, "X", 9); // This tool needs to be set with the original type of X, which cannot be automatically converted.

 

Summary:Reflection learning is still relatively easy. In my own simplest words, it is described as: Get the class bytecode through reflection and reflect various things in the class. The introspection step is to obtain the attribute description before you can perform the introspection operation on the JavaBean.

 

 

 

 

 

Related Article

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.