Introduction to the Java introspection mechanism

Source: Internet
Author: User
Introduction to the Java introspection mechanism         introspection is the Java language's approach to Bean class properties and events (that is, given a JavaBean object, we can get/ Call it all the Get/set methods). For example, Class A has property name, so we can get the value by Getname,setname or set a new value. The default rule is to access the Name property through Getname/setname. Java provides a set of Getter/setter methods that the API uses to access a property, which allows you to not understand this rule, which is stored in the package Java.beans.     The general practice is to get the BeanInfo information of an object through the class Introspector, and then BeanInfo to get the descriptor (PropertyDescriptor) of the property. This property descriptor allows you to get a Getter/setter method for a property, and then we can invoke these methods through the reflection mechanism. Let's look at an example that prints all the attribute names and values for an object://Defines a JavaBean public class Personbean {   public String name;  & nbsp Public string[] ChildName;    public string[] Getchildname () {      return childname;   }  & nbsp public void Setchildname (string[] childname) {      this.childname = childname;   }    public String GetName () {      return name;   }    Public void SetName (String name) {      this.name = name;   }}  //define a test class to perform the set and The invocation of the Get method is an example of import java.beans.BeanInfo; Import java.beans.IntrospectionException; Import Java.beans.Introspector; Import Java.beans.PropertyDescriptor; Import java.lang.reflect.InvocationTargetException; public class Testintrospector {   public static void Main (string[] args) throws IllegalArgumentException, &nbsp ;                           illegalaccessexception, SecurityException, Nosuchmethodexception,                             InvocationTargetException, Introspectionexception { // Demonstrates the invocation of the Get method      //initialization of a JavaBean object       Personbean pb=new PersonBean ();       pb.setname ("Kangjian");       string[] childs=new string[]{"KK", "JJ", "NN"};       Pb.setchildname (Childs);      //Put the attributes in the JavaBean into the BeanInfo. The second argument is the cutoff parameter, which indicates that        does not include this class until this class. If you do not, you will get info for this class and all of its parent classes.       BeanInfo Bi=introspector.getbeaninfo (Pb.getclass (), object.class);      //encapsulating information for each attribute into a propertydescriptor to form an array          includes attribute names, read-write methods, types of attributes, etc.       propertydescriptor[] pd=bi.getpropertydescriptors ();      //Demo how get       for (int i = 0; i < pd.length; i++) {&NBSP;&NB sp;       if (Pd[i].getpropertytype (). IsArray ())  //getpropertytype Gets the property type.          {           //getreadmethod () Gets the----method object for this property, and then invokes this method with Invoke              string[] result= (string[]) Pd[i].getreadmethod (). Invoke (Pb, null);             System.out.println (Pd[i].getname () + ":"); GetName Gets the property name             for (int j = 0; J < Result.length; j + +) {               System.out.println ( RESULT[J]);            }          }          Else          {             System.out.println (Pd[i].getname () + ":" +pd[i] . Getreadmethod (). Invoke (Pb, null));         }      }  //demo The Call of the Set method      //Initialize a JavaBean      with no set   Personbean pb0=new Personbean ();      //simulation of a data (data name and JavaBean attribute name consistent)       String name= "Luonan";       string[] childname=new string[]{"Luo", "Nan"};         BeanInfo Bi0=introspector.getbeaninfo (Pb0.getclass (), object.class);       propertydescriptor[] Pd0=bi0.getpropertydescriptors ();         for (int i = 0; i < pd0.length; i++) {          if (Pd0[i].getpropertytype (). IsArray ())          {             if (Pd0[i].getname (). Equals ("ChildName"));             {                if (Pd0[i].getpropertytype (). Getcomponenttype (). Equals (String.class))                 {//getcomponenttype () can get the element type of the array type                   // Getwritemethod () Gets the set method of this property---the Method object, and then invokes this approach with invoke                    Pd0[i].getwritemethod (). Invoke (Pb0,new object[]{childname});               }             }         }           Else          {             if (Pd0[i].getname (). Equals ("name"));             {               pd0[i]. Getwritemethod (). Invoke (Pb0,name);            }          }      }         System.out.println (Pb0.getname ());       string[] Array=pb0.getchildname ();       for (int i = 0; i < Array.Length i++) {       &nbs P System.out.println (Array[i]);      }   }} More difficult applications please refer to http://hi.baidu.com/shunxinyangkun/blog/item/ dd2c4ff46ae61aeb7609d7ba.html   Ii. Thinking about introspection     struts2 action (and Struts1 Formbean) is the way to achieve it. The     foreground form tag has attributes (known in the configuration file that the form is submitted to that action, which has an attribute corresponding to the form and its get/set), and after submission, Stopped by Struts's servlet to forward a specific action. Before forwarding to the action, struts passes the value set in the form to the action in an introspective manner.     In fact, as long as there is a set** or get**, introspection will understand that there is such a * * attribute, so that we can make the Bean class through an interface to define without caring about the implementation, do not care about the data stored in the bean. For example, we can put all the Getter/setter methods into the interface definition, but the real data access is in the specific class to implement, so as to improve the system scalability.   III. summarizing     applying Java reflection and introspection to program design can greatly provide intelligent and scalable programs. There are a number of projects that take these two technologies to achieve their core functions, such as the Struts we mentioned earlier, and the Digester project for working with XML files, which should be said to be more or less used by almost all projects. In the practical application process, the two should be combined with each other to play a real intelligent and highly scalable.   Original link Address: http://polaris.blog.51cto.com/1146394/273614

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.