BeanUtils學習總結

來源:互聯網
上載者:User

一、BeanUtils介紹

BeanUtils是apache的開發庫;

為了使用BeanUtils,需要匯入

(1)common-logging-1.1.1.jar

(2)common-beanutils.jar

二、BeanUtils開發(1)設定屬性;(2)註冊轉換器;(3)自訂轉換器;(4)大量設定屬性; 注意:JavaBean必須是public的,不然BeanUtils會拋異常;
package org.xiazdong.beanutils;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConversionException;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.Converter;import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;import org.junit.Test;import org.xiazdong.Person;public class Demo01 {// 設定屬性@Testpublic void test1() throws Exception {Person p = new Person();BeanUtils.setProperty(p, "name", "xiazdong");BeanUtils.setProperty(p, "age", 20);System.out.println(p.getName());System.out.println(p.getAge());}// 自訂轉換器@Testpublic void test2() throws Exception {Person p = new Person();ConvertUtils.register(new Converter() {@Overridepublic Object convert(Class type, Object value) {if (value == null) {return null;}if (!(value instanceof String)) {throw new ConversionException("conversion error");}String str = (String) value;if (str.trim().equals("")) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");try {return sdf.parse(str);} catch (ParseException e) {throw new RuntimeException(e);}}}, Date.class);BeanUtils.setProperty(p, "birth", "2011-10-10");System.out.println(p.getBirth().toLocaleString());}// 使用內建的轉換器@Testpublic void test3() throws Exception {Person p = new Person();ConvertUtils.register(new DateLocaleConverter(), Date.class);BeanUtils.setProperty(p, "birth", "2011-10-10");System.out.println(p.getBirth().toLocaleString());}// 使用內建的轉換器@Testpublic void test4() throws Exception {Map map = new HashMap();map.put("name", "xiazdong");map.put("age", "20");map.put("birth", "2010-10-10");ConvertUtils.register(new DateLocaleConverter(), Date.class);Person p = new Person();BeanUtils.populate(p, map);System.out.println(p.getAge());System.out.println(p.getBirth());}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.