Skip to content
LOCZH/安大略 · 加拿大待机OK/--:--:--EST
M4M4RK_YUportfolio
  • 项目
    项目Overview
    • 作品精选案例与项目记录
    • 游戏可玩原型与游戏开发日志
  • 影像
    影像Overview
    • 档案影像合集与视觉实验
    • 商店印刷品、海报和限量物件
  • 日志
    日志Overview
    • 博客长篇开发日志与现场笔记
    • 笔记短观察、链接与代码片段
  • 资源
    资源Overview
    • 工具38 款浏览器内开发工具
    • 链接每日使用的开发与设计书签
  • 关于
  • 联系
EN

同步 · dev.to / @markyu

Advanced Java: Simplifying Object Property Copy and Manipulation with BeanUtil

In Java programming, the BeanUtil utility class is a powerful and convenient tool for simplifying the...

发布日期
May 26 '24
·
阅读时长
5 min read
·
点赞
12
·
评论数
2
javajavabeansspringframeworkobjectmapping
在 dev.to 查看评论

In Java programming, the BeanUtil utility class is a powerful and convenient tool for simplifying the process of copying properties and manipulating objects. This article will introduce the basic functionalities of BeanUtil, demonstrate its application through detailed code examples, and compare it with other similar tools. Additionally, we will explore the advantages and usage scenarios of BeanUtil in real-world development to help developers better understand and utilize this utility class.

Introduction to the BeanUtil Utility Class

1. Overview of BeanUtil

BeanUtil is a widely used Java utility class that provides a series of methods to simplify property copying and manipulation between JavaBean objects. It primarily addresses complex object operations and property handling issues, significantly improving code readability and maintainability.

Shallow Copy vs. Deep Copy:

  • Shallow Copy: BeanUtil performs shallow copying, meaning it copies values for primitive data types and references for object types. This means that while the values of primitive types are directly copied, the references to objects are copied instead of the objects themselves. As a result, changes to these objects in one instance will affect the other.
  • Deep Copy: In contrast, deep copying involves creating new objects for referenced types and copying their content. This ensures that the objects in the new instance are entirely independent of those in the original instance.

2. Core Features of BeanUtil

The core functionalities of BeanUtil include:

FeatureDescription
copyPropertiesCopies property values from one object to another
setPropertySets the value of a specified property of an object
getPropertyGets the value of a specified property of an object
cloneBeanClones an object, creating a duplicate
populatePopulates an object's properties using data from a Map
describeConverts an object's properties and values into a Map

These features make BeanUtil incredibly versatile, enabling developers to handle complex property manipulations with minimal code.

3. Comparison with Similar Libraries

In addition to BeanUtil, there are several other tools and libraries available for object property copying and manipulation:

  • Apache Commons BeanUtils: Provides utility methods for JavaBean operations, including property copying and setting. It's an open-source library widely used in Java projects.
  • Spring BeanUtils: A utility class from the Spring Framework that offers simple property copying and manipulation methods, commonly used within the Spring ecosystem.
  • Dozer: A Java Bean mapper that supports deep copying and complex mapping configurations. It allows for custom mapping configurations, suitable for complex object conversions.
  • ModelMapper: An intelligent object mapping framework designed to simplify the mapping between objects. It offers powerful mapping capabilities and handles complex object relationships and type conversions.
  • MapStruct: A compile-time code generator that automatically generates type-safe, high-performance Bean mapping code. It uses annotation-driven mapping definitions, reducing runtime overhead.
  • Orika: A Java Bean mapper focused on providing fast and simple object mapping capabilities. It supports complex mapping configurations and multiple mapping strategies, making it ideal for high-performance mapping needs.

Comparison Table:

Tool ClassProperty CopyProperty Set/GetType ConversionPerformanceConfiguration Complexity
BeanUtilYesYesYesMediumLow
Apache BeanUtilsYesYesYesLowLow
Spring BeanUtilsYesYesNoHighLow
DozerYesNoYesLowMedium
ModelMapperYesNoYesMediumMedium
MapStructYesNoYesHighHigh
OrikaYesNoYesMediumMedium

These tools each have their unique features, and developers can choose the most suitable one based on project requirements. For instance, Apache Commons BeanUtils and Spring BeanUtils are ideal for simple property copying, while Dozer and ModelMapper are better suited for complex object mapping needs. MapStruct and Orika excel in performance and type safety.

Using BeanUtil: Code Examples

1. Property Copying

Property copying is one of the most common functions of BeanUtil, allowing you to copy all property values from one object to another.

Example Code:

import org.apache.commons.beanutils.BeanUtils;

public class BeanUtilExample {
    public static void main(String[] args) {
        try {
            SourceObject source = new SourceObject("John", 30);
            TargetObject target = new TargetObject();
            
            BeanUtils.copyProperties(target, source);
            
            System.out.println("Target Object: " + target);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class SourceObject {
    private String name;
    private int age;

    public SourceObject(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getters and setters
}

class TargetObject {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "TargetObject [name=" + name + ", age=" + age + "]";
    }

    // getters and setters
}

In this example, the copyProperties method copies the property values from the source object to the target object.

2. Setting and Getting Properties

BeanUtil also provides methods for dynamically setting and getting object properties.

Example Code:

import org.apache.commons.beanutils.BeanUtils;

public class PropertyExample {
    public static void main(String[] args) {
        try {
            MyBean myBean = new MyBean();
            BeanUtils.setProperty(myBean, "name", "Alice");
            BeanUtils.setProperty(myBean, "age", 25);

            String name = BeanUtils.getProperty(myBean, "name");
            String age = BeanUtils.getProperty(myBean, "age");

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyBean {
    private String name;
    private int age;

    // getters and setters
}

In this example, setProperty is used to set the name and age properties of myBean, and getProperty is used to retrieve these values.

3. Object Cloning

BeanUtil can also clone objects, creating duplicates.

Example Code:

import org.apache.commons.beanutils.BeanUtils;

public class CloneExample {
    public static void main(String[] args) {
        try {
            MyBean original = new MyBean("Bob", 40);
            MyBean clone = (MyBean) BeanUtils.cloneBean(original);

            System.out.println("Original: " + original);
            System.out.println("Clone: " + clone);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyBean {
    private String name;
    private int age;

    public MyBean() {}

    public MyBean(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "MyBean [name=" + name + ", age=" + age + "]";
    }

    // getters and setters
}

In this example, the cloneBean method creates a copy of the original object.

Conclusion

The BeanUtil utility class provides Java developers with a straightforward method for manipulating JavaBean object properties. By using BeanUtil, developers can reduce repetitive code, increase development efficiency, and enhance code readability and maintainability. Although there are many similar tools and libraries, BeanUtil remains a popular choice in many projects due to its simplicity and powerful functionality. Choosing the right tool should depend on the specific needs and complexity of the project. For simple property copying and operations, BeanUtil is an excellent choice, while more complex mapping needs may require other powerful mapping tools. This article, with detailed introductions and example code, aims to help developers better understand and utilize the BeanUtil utility class to improve development efficiency and code quality.

References

  • Apache Commons BeanUtils Documentation
  • Spring Framework BeanUtils Documentation
  • Dozer Documentation
  • ModelMapper Documentation
  • MapStruct Documentation
  • Orika Documentation

相关阅读

java

☕Understanding `final`, `finally`, and `finalize` in Java

Java programming involves a myriad of keywords, each serving distinct purposes to enhance the...

java

Understanding the `throw` and `throws` Keywords in Java

Exception handling is a crucial aspect of Java programming, allowing developers to manage and respond...

database

The True Cost of Poor Data Quality: Why It Matters and How to Improve It

In today’s fast-paced, data-driven world, businesses have more access to data than ever before....

原文发布

本文首发于 dev.to,评论与点赞保留在原站。

在 dev.to 继续阅读
上一篇RedisJSON: Enhancing JSON Data Handling in RedisIntroduction JSON has become the standard format for data exchange in modern...
返回档案
下一篇How to Determine the Network Address from a Known IP AddressEver wondered how devices communicate within a network? Or perhaps you've come across terms like "IP...
返回档案
频道开放·随时打个招呼 · 2026
--:--:--EST
联系

看到什么有意思的?和我聊聊。

这是一个作品集,不是服务 · 但每一条留言我都会看 — 如果哪里让你有所触动,或者只想打个招呼,欢迎写信过来。

开启对话

订阅

偶尔收到一封简讯

来自 m4rkyu.com 的笔记与日志——简短、标注日期、没有杂音。随时可退订。

作品

线上发布、游戏作品与视觉档案。

  • 项目
  • 游戏
  • 档案
  • 日志

资源

每日好用的工具与个人收藏的链接库。

  • 搜索
  • 最新
  • 工具
  • 链接
  • 笔记
  • 主题
  • RSS
  • JSON Feed
  • 商店

工作室

背景、联系方式以及合作渠道。

  • 关于
  • 联系
  • 更新日志
  • 技术说明
  • 简历筹备中

社交

在常去的平台上找到我。

  • Facebook敬请期待
  • Instagram敬请期待
  • YouTube敬请期待
  • 领英敬请期待
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
始于 2024
ZhenXiao Mark YuZhenXiao Mark Yu
© 2026 ZhenXiao Mark Yu·加拿大 安大略
  • 邮件
  • GitHub
  • dev.to
  • 领英 (敬请期待)
  • 推特 / X (敬请期待)
  • Instagram (敬请期待)
由 Next.js 16 · React 19 · Tailwind 4 构建

由 Next.js 16 · React 19 · Tailwind 4 构建