MutablePropertyValues的簡單用法


代碼例子:

 1 package com.cy.model;
 2 
 3 import lombok.Getter;
 4 import lombok.Setter;
 5 import lombok.ToString;
 6 
 7 @Getter
 8 @Setter
 9 @ToString
10 public class Apple {
11     private String id;
12     private String name;
13 }
View Code


MutablePropertyValues的使用:

 1 package com.cy.test.spring;
 2 
 3 import com.cy.model.Apple;
 4 import org.springframework.beans.BeanWrapper;
 5 import org.springframework.beans.MutablePropertyValues;
 6 import org.springframework.beans.PropertyAccessorFactory;
 7 
 8 public class TestMutablePropertyValues {
 9 
10     public static void main(String[] args) {
11         //Apple的屬性名稱
12         String[] properties = new String[]{"id", "name"};
13         MutablePropertyValues pvs = new MutablePropertyValues();
14 
15         for(int i=0; i<properties.length; i++){
16             String property = properties[i];
17             String value = "test" + i;
18             pvs.add(property, value);
19         }
20 
21         Apple p = new Apple();
22         BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(p);
23         wrapper.setPropertyValues(pvs);
24         System.out.println(p);
25     }
26 }

打印結果:

Apple(id=test0, name=test1)

注:

1.MutablePropertyValues中設置的屬性值類型,要和Apple中屬性對應的值類型要匹配,不然會報錯。java.lang.NumberFormatException等等。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM