BeanUtils


前言

Apache BeanUtils是一种方便我们对JavaBean进行操作的工具类。

阿里巴巴java开发手册(泰山版):
在这里插入图片描述

从上图中可以看出实际开发中我们应选择 Spring BeanUtils,一方面不需要额外引入依赖包,另一方面性能会比Apache BeanUtils 性能好(同理的还有 Spring StringUtils),所以【本文内容仅做了解】!!!


推荐文章

不考虑性能,从拓展性角度看看!BeanUtils还是有很多问题的!

  • 复制对象时字段类型不一致,导致赋值不上,你怎么解决?自己拓展?
  • 复制对象时字段名称不一致,例如CarPo里叫carName,CarVo里叫name,导致赋值不上,你怎么解决?自己拓展?
  • 如果是集合类的复制,例如List<CarPo>转换为List<CarVo>,你怎么处理?
    (省略一万字…)

【如何优雅的转换Bean对象】

【Java 实体映射工具 MapStruct】


Maven依赖

在这里插入图片描述

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

常用API

// 把orig对象copy到dest对象中.
public void copyProperties (Object dest, Object orig)

// 把Bean的属性值放入到一个Map里面
public Map describe(Object bean)

// 把map里面的值放入bean中
public void populate (Object bean, Map map)

// 设置Bean对象中名称为name的属性值赋值为value.	
public void setProperty(Object bean,String name, Object value)

// 取得bean对象中名为name的属性的值
public String getProperty(Object bean, String name)	

常见使用场景

  • 同类之间不同对象要求进行数据复制
User user1 = new User();
user1.setName("张三");
User user2 = new User();
// 把user1复制给user2
BeanUtils. copyProperties(user2,user1);
  • 不同类不同对象之间的数据复制
UserForm userForm =  new UserForm ();
User user =  new User();
// 把userForm 复制给user 
BeanUtils. copyProperties(user, userForm);
  • 对象数据和Map之间互相转化
User user = new User();
// 将对象转换为Map
Map userMap = BeanUtils.describe(user);

Map userMap = new HashMap();
User user = new User();
// 将Map转换为对象
BeanUtils.populate(user,userMap);

日期类型的拷贝

BeanUtils.copyProperties支持Date类型:
【转】BeanUtils.copyProperties支持Date类型

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.log4j.Logger;
 
/**
 * 扩展BeanUtils.copyProperties支持data类型
 */
public class BeanUtilsEx extends BeanUtils {
	private static Logger logger = Logger.getLogger(BeanUtilsEx.class);
 
	static {
		ConvertUtils.register(new DateConvert(), java.util.Date.class);
		ConvertUtils.register(new DateConvert(), String.class);
	}
 
	public static void copyProperties(Object target, Object source) {
		// 支持对日期copy
		try {
			org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException | InvocationTargetException e) {
			logger.error("扩展BeanUtils.copyProperties支持data类型:" + e.getMessage());
			e.printStackTrace();
		}
	}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
 
/**
 * 扩展BeanUtils.copyProperties支持data类型
 */
public class DateConvert implements Converter {
	@Override
	public Object convert(Class class1, Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof Date) {
			return value;
		}
		if (value instanceof Long) {
			Long longValue = (Long) value;
			return new Date(longValue.longValue());
		}
		if (value instanceof String) {
			String dateStr = (String) value;
			Date endTime = null;
			try {
				String regexp1 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp2 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])(/t)([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp3 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])";
				if (dateStr.matches(regexp1)) {
					dateStr = dateStr.split("T")[0] + " " + dateStr.split("T")[1];
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp2)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp3)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else {
					return dateStr;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return value;
	}
}

封装工具类

把请求中的参数拷贝到javaBean对象中

// 约定前提: 请求中的参数名称需要和javabean的属性名称保持一致!!!!
public static <T>T requestToBean(HttpServletRequest request , Class<T> clazz) {
    //创建javaBean对象    
    Object obj=null;
    try {
        obj=clazz.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    
    //得到请求中的每个参数
    Enumeration<String> enu = request.getParameterNames();
    while(enu.hasMoreElements())  {
        //获得参数名
        String name = enu.nextElement();
        
        //获得参数值
        String value = request.getParameter(name);
        
        //然后把参数拷贝到javaBean对象中
        try {
            BeanUtils.setProperty(obj, name, value);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    return (T)obj;
}
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值