1、commons-beanutils的使用
commons-beanutils-1.9.3.jar 依賴 commons-logging-1.2.jar
代碼1:
String className = "cn.itcast.domain.Person"; Class clazz = Class.forName(className); Object bean = clazz.newInstance(); BeanUtils.setProperty(bean, "name", "張三"); BeanUtils.setProperty(bean, "age", "20"); // age是int類型,會自動轉換 BeanUtils.setProperty(bean, "xxx", "XXX"); // 沒有xxx屬性,也不會拋異常 String age = BeanUtils.getProperty(bean, "age");
代碼2:
需求:把map中的屬性直接封裝到一個bean類中。map:{"username:zhangsan","password:123"}。 我們要把map的數據封裝到一個javaBean中!要求map的key值於bean的屬性名相同。
首先,新建一個javabean,User.java 有兩個屬性username,password。
public void fun1() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("username", "zhangsan"); map.put("password", "123"); User user = new User(); BeanUtils.populate(user, map); System.out.println(user); // User [username=zhangsan, password=123] }
代碼3:封裝工具類(用到泛型)
public class CommonUtils {// 把一個Map轉換成指定類型的javabean對象 public static <T> T tobean(Map<String, ?> map, Class<T> clazz) { try { T bean = clazz.newInstance(); BeanUtils.populate(bean, map); return bean; } catch (Exception e) { throw new RuntimeException(e); } } }
2、測試封裝的工具類
package com.oy; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * @author oy * @version 1.0 * @date 2019年5月7日 * @time 下午10:10:35 */ public class User { private Integer id; private String name; private Boolean status; private BigDecimal balance; private Double salary; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("id", 1); map.put("name", "張三"); map.put("status", true); map.put("balance", 1000.123456789); map.put("salary", 1000.123456789); System.out.println(CommonUtils.tobean(map, User.class)); } //getter、setter和toString方法省略 }
map的key對應的值全部寫成字符串格式也是可以的:
Map<String, Object> map = new HashMap<>(); map.put("id", "1"); map.put("name", "張三"); map.put("status", "true"); map.put("balance", "1000.123456789"); map.put("salary", "1000.123456789"); // User [id=1, name=張三, status=true, balance=1000.123456789, salary=1000.123456789] System.out.println(CommonUtils.tobean(map, User.class));
