Deep understanding of Java: Introspection (introspector)

Source: Internet
Author: User
Tags naming convention

Introspection (introspector) is a default processing method of the Java language for JavaBean class properties and events.

JavaBean is a special class that is used primarily to pass data information, in which methods are used primarily to access private fields, and the method name conforms to some naming convention. If you pass information between two modules, you can encapsulate the information into JavaBean, which is called a value object, or VO. method is less than. This information is stored in the private variables of the class, obtained through set (), get ().

For example, class UserInfo:

Package Com.peidasoft.introspector;public class UserInfo {        private long userId;    Private String userName;    private int age;    Private String EmailAddress;        Public long GetUserId () {        return userId;    }    public void Setuserid (long userId) {        this.userid = userid;    }    Public String GetUserName () {        return userName;    }    public void Setusername (String userName) {        this.username = userName;    }    public int getage () {        return age;    }    public void Setage (int.) {        this.age = age;    }    Public String getemailaddress () {        return emailaddress;    }    public void setemailaddress (String emailaddress) {        this.emailaddress = EmailAddress;    }    }

There is a property userName in class UserInfo, so we can get its value by Getusername,setusername or set a new value. The Username property is accessed through Getusername/setusername, which is the default rule. The Java JDK provides a set of Getter/setter methods that the API uses to access a property, which is introspection.

  JDK Introspection Class Library:

  PropertyDescriptor class :

The PropertyDescriptor class indicates that the JavaBean class exports a property through memory. Main methods:
1. Getpropertytype (), gets the property of the class object;
2. Getreadmethod (), obtain the method used to read the property value, Getwritemethod (), get the method to write the property value;
3. Hashcode (), gets the hash value of the object;
4. Setreadmethod (method Readmethod), set the way to read the value of the property;
5. Setwritemethod (method Writemethod), set methods for writing property values.

The instance code is as follows:

Package Com.peidasoft.introspector;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;public class Beaninfoutil {  
public static void SetProperty (UserInfo userinfo,string userName) throws exception{ PropertyDescriptor propdesc= New PropertyDescriptor (Username,userinfo.class); Method Methodsetusername=propdesc.getwritemethod (); Methodsetusername.invoke (UserInfo, "Wong"); System.out.println ("Set UserName:" +userinfo.getusername ()); }
public static void GetProperty (UserInfo userinfo,string userName) throws exception{ PropertyDescriptor Prodescriptor =new PropertyDescriptor (username,userinfo.class); Method Methodgetusername=prodescriptor.getreadmethod (); Object Objusername=methodgetusername.invoke (userInfo); System.out.println ("Get UserName:" +objusername.tostring ());

  Introspector class:

Encapsulates the attributes in the JavaBean to manipulate them. In the program to see a class as JavaBean, is called the Introspector.getbeaninfo () method, the resulting BeanInfo object encapsulates the class as javabean see the result of the information, that is, the property information.

Getpropertydescriptors (), to get the description of the property, you can use the traversal BeanInfo method to find, set the properties of the class. The specific code is as follows:

Package Com.peidasoft.introspector;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;public class Beaninfoutil {public static void SE Tpropertybyintrospector (UserInfo userinfo,string userName) throws exception{BeanInfo Beaninfo=introspector.getbeani        NFO (Userinfo.class);        Propertydescriptor[] Prodescrtptors=beaninfo.getpropertydescriptors ();                if (prodescrtptors!=null&&prodescrtptors.length>0) {for (PropertyDescriptor propdesc:prodescrtptors) { if (Propdesc.getname (). Equals (UserName)) {Method Methodsetusername=propdesc.getwritemetho                    D ();                    Methodsetusername.invoke (UserInfo, "Alan");                    System.out.println ("Set UserName:" +userinfo.getusername ());                Break }}}} public static void Getpropertybyintrospector (UserInfo userinfo,string userName) throWS exception{BeanInfo beaninfo=introspector.getbeaninfo (userinfo.class);        Propertydescriptor[] Prodescrtptors=beaninfo.getpropertydescriptors ();                if (prodescrtptors!=null&&prodescrtptors.length>0) {for (PropertyDescriptor propdesc:prodescrtptors) { if (Propdesc.getname (). Equals (UserName)) {Method Methodgetusername=propdesc.getreadmethod                    ();                    Object Objusername=methodgetusername.invoke (UserInfo);                    System.out.println ("Get UserName:" +objusername.tostring ());                Break }            }        }    }    }

By comparing these two classes, you can see that you need to get propertydescriptor, just in a different way: the former is obtained directly by creating the object, the latter needs to traverse, so it is more convenient to use the PropertyDescriptor class.

Usage examples:

Package Com.peidasoft.introspector;public class Beaninfotest {    /**     * @param args */public    static void Main (string[] args) {        UserInfo userinfo=new UserInfo ();        Userinfo.setusername ("Peida");        try {            beaninfoutil.getproperty (userInfo, "userName");                        Beaninfoutil.setproperty (UserInfo, "userName");                        Beaninfoutil.getproperty (UserInfo, "userName");                        Beaninfoutil.setpropertybyintrospector (UserInfo, "userName");                                    Beaninfoutil.getpropertybyintrospector (UserInfo, "userName");                        Beaninfoutil.setproperty (UserInfo, "age");                    } catch (Exception e) {            //TODO auto-generated catch block            e.printstacktrace ();        }    }}

Output:

Get Username:peidaset username:wongget username:wongset username:alanget userName: Alanjava.lang.IllegalArgumentException:argument type mismatch at    sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)    At Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:39) at    Sun.reflect.DelegatingMethodAccessorImpl.invoke (delegatingmethodaccessorimpl.java:25) at    Java.lang.reflect.Method.invoke (method.java:597) at    Com.peidasoft.Introspector.BeanInfoUtil.setProperty ( beaninfoutil.java:14) at    Com.peidasoft.Introspector.BeanInfoTest.main (beaninfotest.java:22)

Description: Beaninfoutil.setproperty (UserInfo, "age"); the error is that the Age property is an int data type, and the value assigned to the Age property by default in the SetProperty method is a string type. Therefore, the argument type mismatch parameter type mismatch error message will be burst.

Beanutils Toolkit:

As can be seen from the above, the introspection operation is very cumbersome, so Apache developed a simple, easy-to-use API to manipulate Bean Properties--beanutils Toolkit.
Beanutils Toolkit: Download: http://commons.apache.org/beanutils/Note: A logging package is also required when applying http://commons.apache.org/logging/
Use the Beanutils Toolkit to complete the above test code:

Package Com.peidasoft.beanutil;import Java.lang.reflect.invocationtargetexception;import Org.apache.commons.beanutils.beanutils;import Org.apache.commons.beanutils.propertyutils;import Com.peidasoft.introspector.userinfo;public class Beanutiltest {public static void main (string[] args) {Userinf         o userinfo=new userInfo ();                        try {beanutils.setproperty (userInfo, "UserName", "Peida");                        System.out.println ("Set UserName:" +userinfo.getusername ());                        System.out.println ("Get UserName:" +beanutils.getproperty (UserInfo, "userName"));            Beanutils.setproperty (UserInfo, "age", 18);                        System.out.println ("Set Age:" +userinfo.getage ());                         System.out.println ("Get Age:" +beanutils.getproperty (UserInfo, "age"));            System.out.println ("Get userName Type:" +beanutils.getproperty (UserInfo, "UserName"). GetClass (). GetName ()); System.out.println ("Get Age Type:" +bEanutils.getproperty (UserInfo, "age"). GetClass (). GetName ());            Propertyutils.setproperty (UserInfo, "age", 8);                        System.out.println (Propertyutils.getproperty (UserInfo, "age"));                              System.out.println (Propertyutils.getproperty (UserInfo, "age"). GetClass (). GetName ());           Propertyutils.setproperty (UserInfo, "Age", "8");        } catch (Illegalaccessexception e) {e.printstacktrace ();        } catch (InvocationTargetException e) {e.printstacktrace ();        } catch (Nosuchmethodexception e) {e.printstacktrace (); }    }}

Operation Result:

Set Username:peidaget username:peidaset age:18get age:18get userName type:java.lang.Stringget Age Type: Java.lang.String8java.lang.IntegerException in thread "main" Java.lang.IllegalArgumentException:Cannot invoke Com.peidasoft.Introspector.UserInfo.setAge on Bean class ' class com.peidasoft.Introspector.UserInfo '-argument type Mismatch-had objects of type "java.lang.String" but expected signature "int." at Org.apache.commons.beanutils.Property Utilsbean.invokemethod (propertyutilsbean.java:2235) at Org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty (propertyutilsbean.java:2151) at Org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty (propertyutilsbean.java:1957) at Org.apache.commons.beanutils.PropertyUtilsBean.setProperty (propertyutilsbean.java:2064) at Org.apache.commons.beanutils.PropertyUtils.setProperty (propertyutils.java:858) at Com.peidasoft.orm.Beanutil.BeanUtilTest.main (beanutiltest.java:38) caused by:java.lang.IllegalArgumentExceptioN:argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethod Accessorimpl.invoke (nativemethodaccessorimpl.java:39) at Sun.reflect.DelegatingMethodAccessorImpl.invoke ( DELEGATINGMETHODACCESSORIMPL.JAVA:25) at Java.lang.reflect.Method.invoke (method.java:597) at Org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod (propertyutilsbean.java:2170) ... 5 more

Description

1. Get the value of the property, for example, Beanutils.getproperty (UserInfo, "UserName"), return the string
2. Set the value of the property, for example, Beanutils.setproperty (UserInfo, "age", 8), the parameter is a string or the base type is automatically wrapped.   The value of the Set property is a string, and the obtained value is also a string, not a base type. Features of 3.BeanUtils:
1). Operations on attributes of the base data type: In Web development, in use, when input and display, values are converted to strings, but the underlying operation is based on the basic type, and these types go to the action automatically by Beanutils.
2). Operation on a property of a reference data type: First there must be an object in the class, cannot be null, for example, private date birthday=new date ();. Manipulate the object's properties instead of the entire object, for example, Beanutils.setproperty (UserInfo, "Birthday.time", 111111);

Package Com.peidasoft.introspector;import Java.util.date;public class UserInfo {    private Date birthday = new Date (); Public        void Setbirthday (Date birthday) {        this.birthday = birthday;    }    Public Date Getbirthday () {        return birthday;    }      }
Package Com.peidasoft.beanutil;import Java.lang.reflect.invocationtargetexception;import Org.apache.commons.beanutils.beanutils;import Com.peidasoft.introspector.userinfo;public class BeanUtilTest {    public static void Main (string[] args) {        UserInfo userinfo=new UserInfo ();         try {            beanutils.setproperty (userInfo, "Birthday.time", "111111");              Object obj = Beanutils.getproperty (userInfo, "birthday.time");              System.out.println (obj);                  }          catch (Illegalaccessexception e) {            e.printstacktrace ();        }          catch (InvocationTargetException e) {            e.printstacktrace ();        }        catch (Nosuchmethodexception e) {            e.printstacktrace ();}}    }

The 3.PropertyUtils class differs from beanutils in that, when running GetProperty, setproperty operations, there is no type conversion, using either the original type of the property or the wrapper class. Because the data type of the age attribute is int, the method Propertyutils.setproperty (UserInfo, "Age", "8") bursts with data type mismatch and cannot assign a value to the property.

Resources:

1.http://www.cnblogs.com/avenwu/archive/2012/02/28/2372586.html

2.http://blog.csdn.net/zhuruoyun/article/details/8219333

Deep understanding of Java: Introspection (introspector)

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.