標籤:ogg 日期類型 util initial 基本操作 over 支援 line 執行個體
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: 對於基礎資料型別 (Elementary Data Type),會自動進行類型轉換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 @Override18 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 }
java jdbc的最佳化之BeanUtils組件