Commons-BeanUtils中包含大量和JavaBean操做有關的工具方法,提供自動類型轉換,使用BeanUtils可輕鬆利用Java反射機制來完成所需功能。java
使用BeanUtils須要導入commons-beanutils-x.x.x.jar和commons-logging-x.x.jarapache
Apache Commons BeanUtils 1.9.3ide
測試實例測試
package cn.iborder.test; import java.lang.reflect.InvocationTargetException; 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.ConvertUtils; import org.apache.commons.beanutils.Converter; import org.junit.Test; import cn.iborder.entity.Admin; import cn.iborder.entity.Admin1; public class Test2 { @Test public void test1() { Admin admin = new Admin(); try { //實現對象屬性的拷貝 BeanUtils.copyProperty(admin, "userName", "baidu7"); BeanUtils.setProperty(admin, "pwd", "baidu7"); System.out.println(admin.getUserName()+"\t"+admin.getPwd()); //對象拷貝 Admin admin2 = new Admin(); BeanUtils.copyProperties(admin2, admin); System.out.println(admin2.getUserName()+"\t"+admin2.getPwd()); //map數據拷貝到對象 //map中的key應該是javabean的屬性名稱一致 Admin admin3 = new Admin(); Map<String, Object> adminMap = new HashMap<String, Object>(); adminMap.put("userName", "baidu8"); adminMap.put("pwd", "baidu8"); BeanUtils.populate(admin3, adminMap); System.out.println(admin3.getUserName()+"\t"+admin3.getPwd()); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //日期類型轉換器 @Test public void test2() { //模擬表單數據 String name = "jack"; String age = "20"; String birth = "1990-09-22"; //封裝表單數據到對象 Admin1 admin = new Admin(); // 註冊日期類型轉換器 //ConvertUtils.register(new DateLocaleConverter(), Date.class);// 組件提供的轉換器工具類 //自定義 ConvertUtils.register(new Converter() { // 轉換的內部實現方法,須要重寫 @Override public Object convert(Class type, Object value) { if (type != Date.class) { return null; } if (value == null || "".equals(value.toString().trim())) { return null; } try { // 字符串轉換爲日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.parse(value.toString()); } catch (ParseException e) { throw new RuntimeException(e); } } },Date.class); // 把表單提交的數據,封裝到對象中 BeanUtils.copyProperty(admin, "userName", name); BeanUtils.copyProperty(admin, "age", age); BeanUtils.copyProperty(admin, "birth", birth); //------ 測試------ System.out.println(admin); } }