Apache:http://commons.apache.org/proper/commons-beanutils/
BeanUtils工具包是由Apache公司所开发,是Apache commons 组件的成员之一,主要用于简化JavaBean封装数据的操作。简化反射封装参数的步骤,给对象封装参数,BeanUtils给对象封装参数的时候会进行类型自动转换。它可以给JavaBean封装一个字符串数据,也可以将一个表单提交的所有数据封装到JavaBean中。
BeanUtils工具常用工具类有两个:BeanUtils、ConvertUtils。BeanUtils用于封装数据,ConvertUtils用于处理类型转换。
约定前提: 参数名称 需要和javabean的属性名称保持一致!!!!
// https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils
compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.3'
// https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils-core
compile group: 'commons-beanutils', name: 'commons-beanutils-core', version: '1.8.3'
// https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils-bean-collections
compile group: 'commons-beanutils', name: 'commons-beanutils-bean-collections', version: '1.8.3'
// https://mvnrepository.com/artifact/log4j/log4j
compile group: 'log4j', name: 'log4j', version: '1.2.17'
这里还需要 log4j 的api
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
注释:使用 BeanUtils 只需要配置 commons-beanutils-x.x.x.jar 即可,它包含了所有的东西。
import org.apache.commons.beanutils.BeanUtils;
1. public static void setProperty(Object bean, String name, Object value)
给指定对象bean的指定name属性赋值为指定值value。
//如果指定的属性不存在,则什么也不发生。
2.public static String getProperty(Object bean, String name)
获取指定对象bean指定name属性的值。
//如果指定的属性不存在,则会抛出异常。
注意:当属性的类型是数组类型时,获取到的值数组中的第一个值。
3.public static void copyProperties(Object dest, Object orig)
将对象orig的属性值赋值给对象dest对象对应的属性
注意:只有属性名名相同且类型一致的才会赋值成功。
4. public static void populate(Object bean, Map
properties)
将一个Map集合中的数据封装到指定对象bean中
注意:对象bean的属性名和Map集合中键要相同。
public class User {
private int id;
private int age;
private String name;
private double sal;
public User(String name) {
this.name = name;
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
", sal=" + sal +
'}';
}
public void sleep(int i) {
System.out.println(name + "满满的睡了" + i + "小时。。。");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
}
/**
* 对JavaBean的属性进行赋值和取值
* 注意:
* 1. Beanutils给对象设置属性的时候是依赖了setXXX方法。
* 2. BeanUtils获取对象的属性时依赖的是getXXX方法
*/
@Test
public void test() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
//得倒字节码对象
Class clazz = User.class;//Class.forName("com.bug.apache.Utils.BeanUtilsDemo.bean.User");
//利用Class对象创建对象
User s = (User) clazz.newInstance();
//给对象封装数据
BeanUtils.setProperty(s, "id", "001"); //给对象设置属性
//参数一: 对象, 参数二:属性名, 参数三: 属性的值。
BeanUtils.setProperty(s, "name", "小芸");
//参数一: 对象, 参数二:属性名, 参数三: 属性的值。
BeanUtils.setProperty(s, "age", "18");
System.out.println("id:" + BeanUtils.getProperty(s, "id"));
//参数一: 对象, 参数二: 获取的属性的属性名
System.out.println(s);
}
注:
1、BeanUtils的 setProperty(final Object bean, final String name, final Object value) 方法需要的参数分别是
2、BeanUtils的 getProperty(final Object bean, final String name) 方法的返回值是String类型,可以直接输出;
2、对于基本数据类型,beanutils工具进行自动类型转换。把String自动转成Integer,Double,Float。
/**
* Set the specified property value, performing type conversions as
* required to conform to the type of the destination property.
*
* For more details see BeanUtilsBean
.
*
* @param bean Bean on which setting is to be performed
* @param name Property name (can be nested/indexed/mapped/combo)
* @param value Value to be set
*
* @throws IllegalAccessException if the caller does not have
* access to the property accessor method
* @throws InvocationTargetException if the property accessor method
* throws an exception
* @see BeanUtilsBean#setProperty
*/
public static void setProperty(final Object bean, final String name, final Object value)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().setProperty(bean, name, value);
}
/**
* Return the value of the specified property of the specified bean,
* no matter which property reference format is used, as a String.
*
* For more details see BeanUtilsBean
.
*
* @param bean Bean whose property is to be extracted
* @param name Possibly indexed and/or nested name of the property
* to be extracted
* @return The property's value, converted to a String
*
* @throws IllegalAccessException if the caller does not have
* access to the property accessor method
* @throws InvocationTargetException if the property accessor method
* throws an exception
* @throws NoSuchMethodException if an accessor method for this
* property cannot be found
* @see BeanUtilsBean#getProperty
*/
public static String getProperty(final Object bean, final String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return BeanUtilsBean.getInstance().getProperty(bean, name);
}
/**
* 将一个JavaBean对象的属性赋值给另一个JavaBean对象
* 只要两个JavaBean对象的属性名称名称相同就会赋值,不同的不赋值
* 对象中的属性值对拷
*/
@Test
public void test2() throws IllegalAccessException, InstantiationException, InvocationTargetException {
//得到字节码对象
Class clazz = User.class;
//利用Class对象创建对象
User s = (User) clazz.newInstance();
User user = new User("张三",18);
Object obj = new Object();
BeanUtils.copyProperties(s,user);
BeanUtils.copyProperties(obj,user);
System.out.println(s);
System.out.println(obj);
}
public class A{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "A{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class B{
private String name;
private int age;
private String hobby;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "B{" +
"name='" + name + '\'' +
", age=" + age +
", hobby='" + hobby + '\'' +
'}';
}
}
@org.junit.Test
public void test2() throws InvocationTargetException, IllegalAccessException, InstantiationException {
B b = new B();
BeanUtils.setProperty(b,"name","张三");
BeanUtils.setProperty(b,"age",18);
BeanUtils.setProperty(b,"hobby","打牌");
System.out.println(b);//B{name='张三', age=18, hobby='打牌'}
A a = new A();
BeanUtils.setProperty(a,"name","张三");
BeanUtils.setProperty(a,"age",18);
System.out.println(a);//A{name='张三', age=18}
B b2 = new B();
BeanUtils.copyProperties(b2,a);
System.out.println(b2);//B{name='张三', age=18, hobby='null'}
A a2 = new A();
BeanUtils.copyProperties(a2,b);
System.out.println(a2);//A{name='张三', age=18}
}
注释:谨慎使用这个copyproperties这个功能,相同的属性都会被替换,不管是否有值。
/**
* 将一个Map集合的数据封装到一个JavaBean对象中
*/
@Test
public void test3() throws InvocationTargetException, IllegalAccessException {
//创建Map集合
Map map = new HashMap();
String id = "123456";
String name = "封装";
String age = "18";
map.put("id", id);
map.put("name", name);
map.put("age", age);
//给对象封装数据 , 数据全部都在Map中。
User s = new User();
//把map中的数据封装到对象上。
BeanUtils.populate(s, map);
System.out.println("用户信息是:" + s);
}
/**
* 自定义BeanUtils工具类
*/
public static Object populate(Class clazz, Map param) {
Object bean = null;
try {
//利用class对象创建对象
bean = clazz.newInstance();
BeanUtils.populate(bean, param);
} catch (Exception e) {
throw new RuntimeException(e); //如果一个方法内部抛出了一个非运行时异常,那么必须在方法上也要声明抛出。
// 如果一个方法内部抛出了一个运行时异常的时候,方法 上可以声明抛出也可以不声明抛出。
}
return bean;
}
参考:
https://blog.csdn.net/h294590501/article/details/80740002
https://www.cnblogs.com/vmax-tam/p/4159985.html
https://blog.csdn.net/jpzhu16/article/details/51582930
https://blog.csdn.net/Marksinoberg/article/details/51830076