BeanUtils克隆、复制Java对象

1.BeanUtils位于org.apache.commons.beanutils.BeanUtils

依赖:

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

常用方法:populate


static void	populate(Object bean, Map<String,? extends Object> properties)
Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.

这个方法会遍历map<key, value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性

示例

  /**
     * org.apache.commons.beanutils.BeanUtils  populate(Object bean, Map<String,? extends Object> properties)
     */
    @Test
    public void testBeanUtilsFromCommons1() throws InvocationTargetException, IllegalAccessException {

        Person person = new Person();
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "10086");
        map.put("username", "张三");
        map.put("address", "地址");
        BeanUtils.populate(person, map);
        System.out.println(JSON.toJSONString(person));
    }
@Data
public class Person {

    private Long id;
    private String username;
    private int age;

    public Person(Long id, String username, int age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }

    public Person() {
    }
}

结果:

age是int类型,没有赋值时默认值为0, Person没有address属性,所以不赋值。id为Long类型,但是map中为String类型,类型不一样也能得到值,说明内部进行了类型转换
在这里插入图片描述

常用方法:cloneBean

static Object	cloneBean(Object bean)
Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
基于可用的属性getter和setter克隆bean,即使bean类本身没有实现Cloneable

示例:

 /**
     * org.apache.commons.beanutils.BeanUtils  cloneBean(Object bean)
     */
    @Test
    public void testBeanUtilsFromCommons2() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {

        Person person1 = new Person(10086L, "张三", 20);
        Person person2 = (Person)BeanUtils.cloneBean(person1);
        System.out.println("person1:" + JSON.toJSONString(person1));
        System.out.println("person2:" + JSON.toJSONString(person2));
        System.out.println(person1.equals(person2));
        person2.setId(888L);
        System.out.println("person1:" + JSON.toJSONString(person1));
        System.out.println("person2:" + JSON.toJSONString(person2));
    }

结果:
cloneBean将拷贝一份对象,此时person1.equals(person2) 为true, 对person2的id再赋值,不影响person1,说明是两个对象互不影响
在这里插入图片描述

常用方法:copyProperties(Object dest, Object orig)

static void	copyProperties(Object dest, Object orig)
Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
对于所有属性名称相同的情况,将属性值从源bean复制到目标bean。

示例:

 /**
     * org.apache.commons.beanutils.BeanUtils  copyProperties(Object dest, Object orig)
     */
    @Test
    public void testBeanUtilsFromCommons3() throws InvocationTargetException, IllegalAccessException {

        Person person1 = new Person(10086L, "张三", 20);
        Person person2 = new Person();
        BeanUtils.copyProperties(person2, person1);
        System.out.println("person1:" + JSON.toJSONString(person1));
        System.out.println("person2:" + JSON.toJSONString(person2));
    }

结果:
在这里插入图片描述

2.BeanUtils位于org.springframework.beans.BeanUtils

JavaBeans 的静态便捷方法:用于实例化 bean、检查 bean 属性类型、复制 bean 属性等。

常用方法:copyProperties

在这里插入图片描述

修饰符和类型	方法及说明


static void	copyProperties(Object source, Object target)
将给定源 bean 的属性值复制到目标 bean。

static void	copyProperties(Object source, Object target, Class<?> editable)
将给定源 bean 的属性值复制到给定目标 bean 中,仅设置给定“可编辑”类(或接口)中定义的属性。

static void	copyProperties(Object source, Object target, String... ignoreProperties)
将给定源 bean 的属性值复制到给定目标 bean 中,忽略给定的“ignoreProperties”。

示例:copyProperties(Object source, Object target)

 /**
     * org.springframework.beans.BeanUtils    copyProperties(Object source, Object target)
     */
    @Test
    public void testBeanUtilsFromSpringframework1(){


        Person person = new Person(10086L, "张三", 20);
        Person person2 = new Person();
        BeanUtils.copyProperties(person, person2);
        System.out.println(JSON.toJSONString(person2));

    }

结果:
在这里插入图片描述

示例 copyProperties(Object source, Object target, String… ignoreProperties)

    /**
     * org.springframework.beans.BeanUtils
     * static void	copyProperties(Object source, Object target, String... ignoreProperties)
     */
    @Test
    public void testBeanUtilsFromSpringframework2(){


        Person person = new Person(10086L, "张三", 20);
        Person person2 = new Person();
        BeanUtils.copyProperties(person, person2, "username");
        System.out.println(JSON.toJSONString(person2));

    }

结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用BeanUtils类将Java对象转换成Map非常简单,可以按照以下步骤操作: 1. 引入BeanUtils库,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency> ``` 2. 编写Java代码,将Java对象转换成Map,示例代码如下: ```java import org.apache.commons.beanutils.BeanUtils; public class BeanToMapExample { public static void main(String[] args) throws Exception { // 创建Java对象 User user = new User(); user.setId(1L); user.setName("张三"); user.setAge(20); // 将Java对象转换成Map Map<String, String> map = BeanUtils.describe(user); // 打印Map内容 for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } class User { private Long id; private String name; private int age; // 省略getter和setter方法 } ``` 运行结果如下: ``` class: User id: 1 name: 张三 age: 20 ``` 上述代码中,使用BeanUtils.describe方法将Java对象转换成Map,返回的Map中键为属性名,值为属性值。需要注意的是,返回的Map中会包含一个class键,其值为Java对象的类名。如果不需要class键,可以使用BeanUtils.describe方法的重载版本,指定不包含class键,示例代码如下: ```java Map<String, String> map = BeanUtils.describe(user); map.remove("class"); ``` 这样返回的Map中就不包含class键了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值