一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java 內省(Introspector)深入理解

Java 內省(Introspector)深入理解

2020-08-25 11:13Java教程網 Java教程

這篇文章主要介紹了Java 內省(Introspector)深入理解的相關資料,需要的朋友可以參考下

Java 內省(Introspector)深入理解

一些概念:

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

  JavaBean是一種特殊的類,主要用于傳遞數據信息,這種類中的方法主要用于訪問私有的字段,且方法名符合某種命名規則。如果在兩個模塊之間傳遞信息,可以將信息封裝進JavaBean中,這種對象稱為“值對象”(Value Object),或“VO”。方法比較少。這些信息儲存在類的私有變量中,通過set()、get()獲得。

  例如類UserInfo :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 age) {
    this.age = age;
  }
  public String getEmailAddress() {
    return emailAddress;
  }
  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }
  
}

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

  JDK內省類庫:

  PropertyDescriptor類:

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

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

  實例代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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類:

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

  getPropertyDescriptors(),獲得屬性的描述,可以采用遍歷BeanInfo的方法,來查找、設置類的屬性。具體代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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 setPropertyByIntrospector(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 methodSetUserName=propDesc.getWriteMethod();
          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;
        }
      }
    }
  }
  
}

    通過這兩個類的比較可以看出,都是需要獲得PropertyDescriptor,只是方式不一樣:前者通過創建對象直接獲得,后者需要遍歷,所以使用PropertyDescriptor類更加方便。

  使用實例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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();
    }
 
  }
 
}

  輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
get userName:peida
set userName:wong
get userName:wong
set userName:alan
get userName:alan
java.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) 

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

  BeanUtils工具包:

  由上述可看出,內省操作非常的繁瑣,所以所以Apache開發了一套簡單、易用的API來操作Bean的屬性——BeanUtils工具包。

  BeanUtils工具包:下載:http://commons.apache.org/beanutils/ 注意:應用的時候還需要一個logging包 http://commons.apache.org/logging/

  使用BeanUtils工具包完成上面的測試代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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) {
    UserInfo 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();
    }
  }
}

  運行結果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
set userName:peida
get userName:peida
set age:18
get age:18
get userName type:java.lang.String
get age type:java.lang.String
8
java.lang.Integer
Exception 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.PropertyUtilsBean.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.NativeMethodAccessorImpl.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

  說明:

  1.獲得屬性的值,例如,BeanUtils.getProperty(userInfo,"userName"),返回字符串

  2.設置屬性的值,例如,BeanUtils.setProperty(userInfo,"age",8),參數是字符串或基本類型自動包裝。設置屬性的值是字符串,獲得的值也是字符串,不是基本類型。   3.BeanUtils的特點:
    1). 對基本數據類型的屬性的操作:在WEB開發、使用中,錄入和顯示時,值會被轉換成字符串,但底層運算用的是基本類型,這些類型轉到動作由BeanUtils自動完成。
    2). 對引用數據類型的屬性的操作:首先在類中必須有對象,不能是null,例如,private Date birthday=new Date();。操作的是對象的屬性而不是整個對象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111);   

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
  }  
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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();
    }
  }
}

  3.PropertyUtils類和BeanUtils不同在于,運行getProperty、setProperty操作時,沒有類型轉換,使用屬性的原有類型或者包裝類。由于age屬性的數據類型是int,所以方法PropertyUtils.setProperty(userInfo, "age", "8")會爆出數據類型不匹配,無法將值賦給屬性。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 2021国产麻豆剧传媒剧情 | 日韩亚洲一区中文字幕在线 | 天天色天天综合 | 无人在线高清免费看 | 欧美亚洲一区二区三区 | 男生操男生 | 91免费精品国自产拍在线不卡 | 日本一区二区三区精品 | 精品播放 | 无人视频在线观看完整版高清 | 国产成人精品在线观看 | 国产亚洲精品一区在线播 | 91香蕉国产在线观看免费永久 | 好男人免费高清在线观看2019 | 99国内精品久久久久久久黑人 | 99九九国产精品免费视频 | 亚洲成年男人的天堂网 | 欧美一级专区免费大片 | 草莓在线 | 羞羞漫画免费漫画页面在线看漫画秋蝉 | 单身男女韩剧在线看 | 亚洲国产99 | 国产精品色拉拉免费看 | 3d动漫美女被吸乳羞羞有 | 韩国最新理论三级在线观看 | 欧美久久一区二区三区 | 国产a不卡片精品免费观看 国产aaa伦理片 | 欧美特一级 | 久久人妻熟女中文字幕AV蜜芽 | 国产在线欧美日韩精品一区二区 | 草女人逼 | 日日操综合 | 高清在线观看mv的网址免费 | 亚洲第一二三四区 | 我与恶魔的h生活ova | 天天干天天操天天爽 | 亚洲精品卡1卡二卡3卡四卡 | 97香蕉超级碰碰碰久久兔费 | www一级片 | 91国内精品久久久久怡红院 | 亚洲欧美日韩一区成人 |