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等等。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章