国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

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

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

服務器之家 - 編程語言 - Java教程 - Java反射 PropertyDescriptor類案例詳解

Java反射 PropertyDescriptor類案例詳解

2021-11-25 13:04weixin_42069143 Java教程

這篇文章主要介紹了Java反射 PropertyDescriptor類案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下

JAVA中反射機制(JavaBean的內省與BeanUtils庫)

內省(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
36
37
38
39
40
41
package com.peidasoft.instrospector; 
 
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(),獲得用于讀取屬性值的方法;
  3. getWriteMethod(),獲得用于寫入屬性值的方法;
  4. hashCode(),獲取對象的哈希值;
  5. setReadMethod(Method readMethod),設置用于讀取屬性值的方法;
  6. 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
24
25
26
27
28
29
30
31
package com.peidasoft.instrospector; 
 
import java.beans.BeanInfo; 
import java.beans.Introspector; 
import java.beans.PropertyDescriptor; 
import java.lang.reflect.Method; 
 
public class BeanInfoUtil { 
 
    // 設置bean的某個屬性值 
    public static void setProperty(UserInfo userInfo, String userName) throws Exception { 
        // 獲取bean的某個屬性的描述符 
        PropertyDescriptor propDesc = new PropertyDescriptor(userName, UserInfo.class); 
        // 獲得用于寫入屬性值的方法 
        Method methodSetUserName = propDesc.getWriteMethod(); 
        // 寫入屬性值 
        methodSetUserName.invoke(userInfo, "wong"); 
        System.out.println("set userName:" + userInfo.getUserName()); 
    
 
    // 獲取bean的某個屬性值 
    public static void getProperty(UserInfo userInfo, String userName) throws Exception { 
        // 獲取Bean的某個屬性的描述符 
        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
42
43
import java.beans.BeanInfo; 
import java.beans.Introspector; 
import java.beans.PropertyDescriptor; 
import java.lang.reflect.Method; 
 
public class BeanInfoUtil { 
 
    // 通過內省設置bean的某個屬性值 
    public static void setPropertyByIntrospector(UserInfo userInfo, String userName) throws Exception { 
        // 獲取bean信息 
        BeanInfo beanInfo = Introspector.getBeanInfo(UserInfo.class); 
        // 獲取bean的所有屬性列表 
        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
                
            
        
    
 
    // 通過內省獲取bean的某個屬性值 
    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
package com.peidasoft.instrospector; 
 
public class BeanInfoTest { 
 
    /**
     * @param args the command line arguments
     */
    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");  // IllegalArgumentException 
        } catch (Exception e) { 
            e.printStackTrace(); 
        
    
}

輸出結果:

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:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:483) 
    at com.peidasoft.instrospector.BeanInfoUtil.setProperty(BeanInfoUtil.java:22) 
    at com.peidasoft.instrospector.BeanInfoTest.main(BeanInfoTest.java:26)

說明: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
46
47
48
49
50
51
52
53
54
55
56
57
package com.peidasoft.instrospector; 
 
import java.lang.reflect.InvocationTargetException; 
import org.apache.commons.beanutils.BeanUtils; 
import org.apache.commons.beanutils.PropertyUtils; 
 
public class BeanInfoTest { 
 
    /**
     * @param args the command line arguments
     */ 
    public static void main(String[] args) { 
        UserInfo userInfo = new UserInfo(); 
        userInfo.setUserName("peida"); 
        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");  // IllegalArgumentException 
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { 
            e.printStackTrace(); 
        
    
運行結果:
[java] view plain copy
set userName:peida 
get userName:peida 
set age:18 
get age:18 
get userName type:java.lang.String 
get age type:java.lang.String 
 
java.lang.Integer 
Exception in thread "main" java.lang.IllegalArgumentException: Cannot invoke com.peidasoft.instrospector.UserInfo.setAge on bean class  
    'class com.peidasoft.instrospector.UserInfo' - argument type mismatch - had objects of type "java.lang.String" but expected signature "int" 
    at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2181) 
    at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2097) 
    at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1903) 
    at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2010) 
    at org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:896) 
    at com.peidasoft.instrospector.BeanInfoTest.main(BeanInfoTest.java:32) 
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:483) 
    at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2116) 
    ... 5 more

說明:
1. 獲得屬性的值,例如,BeanUtils.getProperty(userInfo, “userName”),返回字符串。
2. 設置屬性的值,例如,BeanUtils.setProperty(userInfo, “age”, 8),參數是字符串或基本類型自動包裝。設置屬性的值是字符串,獲得的值也是字符串,不是基本類型?!  ?. 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(); // 引用類型的屬性,不能為null 
 
    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(); 
        
    
}

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

到此這篇關于Java反射 PropertyDescriptor類案例詳解的文章就介紹到這了,更多相關Java反射 PropertyDescriptor類內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/weixin_42069143/article/details/82119724

延伸 · 閱讀

精彩推薦
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關于小米推送Java代碼,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩中求8032021-07-12
  • Java教程Java實現搶紅包功能

    Java實現搶紅包功能

    這篇文章主要為大家詳細介紹了Java實現搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java BufferWriter寫文件寫不進去或缺失數據的解決

    Java BufferWriter寫文件寫不進去或缺失數據的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進去或缺失數據的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程xml與Java對象的轉換詳解

    xml與Java對象的轉換詳解

    這篇文章主要介紹了xml與Java對象的轉換詳解的相關資料,需要的朋友可以參考下...

    Java教程網2942020-09-17
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發現了對于集合操作轉換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關于Java8中S...

    阿杜7482021-02-04
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經有好久沒有升過級了。升級完畢重啟之后,突然發現好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
主站蜘蛛池模板: 国产欧美精品一区二区三区 | 日韩高清一区二区 | 伊人一区二区三区 | 国产欧美日韩专区 | 国产成人精品一区二区三区网站观看 | 精品久久久网站 | 人人射| 国产成人精品一区二区三区视频 | 一区亚洲| 国产h片在线观看 | 国产片性视频免费播放 | 久久久精品网站 | 国产黄色大片 | 免费激情| 欧美成人精品一区二区 | 亚洲日本欧美日韩高观看 | av在线免费网址 | 欧美精品1区2区3区 日本电影中文字幕 | 美女爽到呻吟久久久久 | 日韩视频区 | 日韩成人影院 | 国产特级毛片aaaaaa毛片 | 久久影院免费观看 | 国内成人自拍视频 | 日韩精品一区二区三区在线播放 | 久久免费精品视频 | 中文字幕乱码亚洲精品一区 | 亚洲日本乱码一区两区在线观看 | 婷婷色综合| 中文字幕在线视频第一页 | 色8888www视频在线观看 | 国偷自产一区二区免费视频 | 午夜专区| 一区二区av在线 | 成人午夜精品一区二区三区 | 亚洲电影在线观看 | 天天天干夜夜夜操 | 欧美日韩中文字幕在线 | 午夜社区| 91成人小视频 | 在线二区 |