1. BeanUtils元件
1.1 簡介
程式中對javabean的操作很頻繁, 是以apache提供了一套開源的api,友善對javabean的操作!即BeanUtils元件。
BeanUtils元件, 作用是簡化javabean的操作!
使用者可以從www.apache.org下載下傳BeanUtils元件,然後再在項目中引入jar檔案!
使用BenUtils元件:
- 引入commons-beanutils-1.8.3.jar核心包
- 引入日志支援包: commons-logging-1.1.3.jar
如果缺少日志jar檔案,報錯:
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
1.2 執行個體, 基本用法
方法1: 對象屬性的拷貝
BeanUtils.copyProperty(admin, "userName", "jack");
BeanUtils.setProperty(admin, "age", 18);
方法2: 對象的拷貝
BeanUtils.copyProperties(newAdmin, admin);
方法3: map資料拷貝到javabean中 【注意:map中的key要與javabean的屬性名稱一緻】
BeanUtils.populate(adminMap, map);
1 // 1:對javabean的基本操作
2 @Test
3 public void test1() throws Exception {
4
5 // 建立User對象
6 User user = new User();
7
8 // a:BeanUtiles元件實作對象屬性的拷貝
9 BeanUtils.copyProperty(user, "userName", "張三");
10 BeanUtils.setProperty(user, "age", 22);
11 // 總結1: 對于基本資料類型,會自動進行類型轉換
12
13 // b:BeanUtiles元件實作對象的拷貝
14 User newuser = new User();
15 BeanUtils.copyProperties(newuser, user);
16
17 // c:beanUtiles元件實作把map資料拷貝到對象中
18 // 先建立個map集合,并給予資料
19 Map<String, Object> maptest = new HashMap<String, Object>();
20 maptest.put("userName", "lzl");
21 maptest.put("age", 21);
22 // 建立User對象
23 User userMap = new User();
24 BeanUtils.populate(userMap, maptest);
25
26 // 測試:
27 System.out.println(userMap);
28 }
1.3 執行個體:日期類型的拷貝
需要注冊日期類型轉換器,2種方式參見下面代碼:
1 // 自定義日期類型轉換器
2 @Test
3 public void Date1() throws Exception {
4
5 // 模拟表單資料
6 String name = "mark";
7 String age = "22";
8 String birth = "1994-09-09";
9
10 // 1:建立對象
11 User user = new User();
12
13 // 2:注冊日期轉換器:自定義的
14
15 ConvertUtils.register(new Converter() {
16
17 @Override
18 public Object convert(Class type, Object value) {
19 // 1:首先對進來的字元串資料進行判斷
20 if (type != Date.class) {
21 return null;
22 }
23 if (value == null || "".equals(value.toString().trim())) {
24 return null;
25 }
26
27 try {
28 // 2:字元串轉換為日期
29 // 格式化日期,定義
30 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
31 return sdf.parse(value.toString());
32 } catch (ParseException e) {
33 throw new RuntimeException(e);
34 }
35 }
36
37 }, Date.class);
38 //這裡使用對象的屬性的拷貝,把所需要的變量(屬性)拷貝到user對象中去
39 BeanUtils.copyProperty(user, "userName", name);
40 BeanUtils.copyProperty(user, "age", age);
41 BeanUtils.copyProperty(user, "birthdayF", birth);
42
43 System.out.println(user);
44 }
轉載于:https://www.cnblogs.com/LZL-student/p/6032509.html