Java 內省(Introspector)和 BeanUtils

人生若只如初見,何事秋風悲畫扇。html

概述

內省(Introspector) 是Java 語言對 JavaBean 類屬性、事件的一種缺省處理方法。java

JavaBean是一種特殊的類,主要用於傳遞數據信息,這種類中的方法主要用於訪問私有的字段,且方法名符合某種命名規則。若是在兩個模塊之間傳遞信息,能夠將信息封裝進JavaBean中,這種對象稱爲「值對象」(Value Object),或「VO」。方法比較少。這些信息儲存在類的私有變量中,經過set()、get()得到。例如UserInfogit

package com.niocoder.test.introspector;

/** * */
 public class UserInfo {
     private String userName;
     private Integer age;
     private String webSite;

     public Integer getAge() {
         return age;
     }

     public void setAge(Integer age) {
         this.age = age;
     }

     public String getUserName() {
         return userName;
     }

     public void setUserName(String userName) {
         this.userName = userName;
     }

     public String getWebSite() {
         return webSite;
     }

     public void setWebSite(String webSite) {
         this.webSite = webSite;
     }
 }


複製代碼

在類UserInfo中有屬性 userName, 那咱們能夠經過 getUserName,setUserName來獲得其值或者設置新的值。經過 getUserName/setUserName來訪問 userName屬性,這就是默認的規則。 Java JDK中提供了一套 API 用來訪問某個屬性的 getter/setter 方法,這就是內省。github

JDK內省類庫:

PropertyDescriptor

PropertyDescriptor類表示JavaBean類經過存儲器導出一個屬性。主要方法:web

  1. getPropertyType(),得到屬性的Class對象;
  2. getReadMethod(),得到用於讀取屬性值的方法;getWriteMethod(),得到用於寫入屬性值的方法;
  3. hashCode(),獲取對象的哈希值;
  4. setReadMethod(Method readMethod),設置用於讀取屬性值的方法;
  5. setWriteMethod(Method writeMethod),設置用於寫入屬性值的方法。
package com.niocoder.test.introspector;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class BeanInfoUtil {
  /** * @param userInfo 實例 * @param propertyName 屬性名 * @throws Exception */
  public static void setProperty(UserInfo userInfo, String propertyName) throws Exception {
      PropertyDescriptor propDesc = new PropertyDescriptor(propertyName, UserInfo.class);
      Method methodSetUserName = propDesc.getWriteMethod();
      methodSetUserName.invoke(userInfo, "鄭龍飛");
      System.out.println("set userName:" + userInfo.getUserName());
  }

  /** * @param userInfo 實例 * @param propertyName 屬性名 * @throws Exception */
  public static void getProperty(UserInfo userInfo, String propertyName) throws Exception {
      PropertyDescriptor proDescriptor = new PropertyDescriptor(propertyName, UserInfo.class);
      Method methodGetUserName = proDescriptor.getReadMethod();
      Object objUserName = methodGetUserName.invoke(userInfo);
      System.out.println("get userName:" + objUserName.toString());
  }
}
複製代碼

Introspector

將JavaBean中的屬性封裝起來進行操做。在程序把一個類當作JavaBean來看,就是調用Introspector.getBeanInfo()方法,獲得的BeanInfo對象封裝了把這個類當作JavaBean看的結果信息,即屬性的信息。spring

getPropertyDescriptors(),得到屬性的描述,能夠採用遍歷BeanInfo的方法,來查找、設置類的屬性。具體代碼以下:apache

package com.niocoder.test.introspector;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class BeanInfoUtil {

  /** * @param userInfo 實例 * @param propertyName 屬性名 * @throws Exception */
   public static void setPropertyByIntrospector(UserInfo userInfo, String propertyName) 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(propertyName)) {
                   Method methodSetUserName = propDesc.getWriteMethod();
                   methodSetUserName.invoke(userInfo, "niocoder");
                   System.out.println("set userName:" + userInfo.getUserName());
                   break;
               }
           }
       }
   }

   /** * @param userInfo 實例 * @param propertyName 屬性名 * @throws Exception */
   public static void getPropertyByIntrospector(UserInfo userInfo, String propertyName) 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(propertyName)) {
                   Method methodGetUserName = propDesc.getReadMethod();
                   Object objUserName = methodGetUserName.invoke(userInfo);
                   System.out.println("get userName:" + objUserName.toString());
                   break;
               }
           }
       }
   }

}

複製代碼

經過這兩個類的比較能夠看出,都是須要得到PropertyDescriptor,只是方式不同:前者經過建立對象直接得到,後者須要遍歷,因此使用PropertyDescriptor類更加方便。socket

Test

BeanInfoTest

public class BeanInfoTest {

    public static void main(String[] args) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("merryyou");
        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();
        }

    }
}
複製代碼

輸出工具

get userName:merryyou
set userName:鄭龍飛
get userName:鄭龍飛
set userName:niocoder
get userName:niocoder
Disconnected from the target VM, address: '127.0.0.1:65243', transport: 'socket'
java.lang.IllegalArgumentException: argument type mismatch
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.niocoder.test.introspector.BeanInfoUtil.setProperty(BeanInfoUtil.java:13)
	at com.niocoder.test.introspector.BeanInfoTest.main(BeanInfoTest.java:19)


複製代碼

說明:BeanInfoUtil.setProperty(userInfo, "age");報錯是應爲age屬性是int數據類型,而setProperty方法裏面默認給age屬性賦的值是String類型。因此會爆出argument type mismatch參數類型不匹配的錯誤信息。this

BeanUtils

由上述可看出,內省操做很是的繁瑣,因此因此Apache開發了一套簡單、易用的API來操做Bean的屬性——BeanUtils工具包。

  • BeanUtils.getProperty(Object bean, String propertyName)
  • BeanUtils.setProperty(Object bean, String propertyName, Object value)

BeanUtilTest

public class BeanUtilTest {

    public static void main(String[] args) {

        UserInfo userInfo = new UserInfo();
        try {

            BeanUtils.setProperty(userInfo, "userName", "鄭龍飛");
            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());
            // 特殊 age屬性爲Integer類型
            PropertyUtils.setProperty(userInfo, "age", "8");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
複製代碼

輸出

set userName:鄭龍飛
get userName:鄭龍飛
set age:18
get age:18
get userName type:java.lang.String
get age type:java.lang.String
8
java.lang.Integer
Disconnected from the target VM, address: '127.0.0.1:50244', transport: 'socket'
Exception in thread "main" java.lang.IllegalArgumentException: Cannot invoke com.niocoder.test.introspector.UserInfo.setAge on bean class 'class com.niocoder.test.introspector.UserInfo' - argument type mismatch - had objects of type "java.lang.String" but expected signature "java.lang.Integer"
	at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2195)
	at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2108)
	at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1914)
	at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2021)
	at org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:896)
	at com.niocoder.test.introspector.BeanUtilTest.main(BeanUtilTest.java:28)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2127)
	... 5 more

Process finished with exit code 1
複製代碼

代碼下載

參考連接

相關文章
相關標籤/搜索