1.背景
在java开发过程中,经常会与javabean打交道,像Entity、pojo、vo、dto等等。java应用非常讲究分层架构,因此在各层之间bean的传输与转换非常的繁琐,比如:
Student stu = new Student();
stu.setName(bean.getName());
stu.setClassName(bean.getClassName());
stu.setPeople(bean.getPeople());
stu.setScore(bean.getScore());
相信大家都会遇到或使用这种方式赋值或取值,这种做法感觉非常恶心,一旦bean的属性很多,增加代码长度不说,还特别影响阅读代码的心情。
为此,业界有很多开源的实现,比如:
apache commons PropertiyUtils
apache commons BeanUrils
Spring BeanUtils
Cglib BeanCopier
Dozer
今天就来探究下apache commons BeanUtils的用法
2.apache commons BeanUtils简介
对于BeanUtils,其实大家都有用到过。它是很多开源项目的基石,比如Struts和Spring,都能看到BeanUtils的影子。用过springMVC框架应该都知道SpringNVC框架中有一个BaseCommandController这个类,这个类的作用就是将前端传过来的参数绑定到特定的对象中去,而不需要我们request.getParamter(“name”);bean.setName(name),从而减少了不少工作。
在Struts中也有这样的功能,用的就是apache BeanUtils这个工具类。
BeanUtils主要是封装了java反射(reflection)和自省(introspection)API,来对javabean进行操作。
这里介绍BeanUtils的几个常用方法:
1.public static Object cloneBean(Object bean) //克隆对象(此处未实现深度clone,复杂对象clone的依然只是引用)
2.public static void copyProperties(Object dest, Object orig) //赋值
3.public static void setProperty(Object bean, String name, Object value) //设置bean中某个属性的值
4.public static String getProperty(Object bean, String name) //得到bean中对应属性值
5.public static void populate(Object bean, Map properties) //Map转为bean
3.BeanUtils使用示例
3.1先定义好bean
package apache.commons.beanutil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class Student implements Serializable{
private int score;
private String className;
private String name;
private People people;
private Date createDate;
public Student() {
}
public Student(int score, String className, String name) {
// TODO Auto-generated constructor stub
this.score = score;
this.className = className;
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
<