CglibUtil

Introduction

CGLib (Code Generation Library) is a powerful, high-performance, and high-quality code generation library that can be used to accomplish dynamic proxying, Bean copying, and other operations.

Hutool added encapsulation of Cglib in version 5.4.1 with CglibUtil to solve the performance issue of Bean copying.

Usage

Introducing Cglib

<dependency>
 <groupId>cglib</groupId>
 <artifactId>cglib</artifactId>
 <version>${cglib.version}</version>
 <scope>compile</scope>
</dependency>

Using CglibUtil

  1. Bean Copying

First, let’s define two Beans:

@Data
public class SampleBean {
 private String value;
}
@Data
public class OtherSampleBean {
 private String value;
}

Note: @Data is a Lombok annotation. Please add getters and setters yourself or introduce the Lombok dependency.

SampleBean bean = new SampleBean();
bean.setValue("Hello world");

OtherSampleBean otherBean = new OtherSampleBean();

CglibUtil.copy(bean, otherBean);

// The value is "Hello world"
otherBean.getValue();

Alternatively, you can omit the target object and pass a class to let Hutool automatically instantiate it for you:

OtherSampleBean otherBean2 = CglibUtil.copy(bean, OtherSampleBean.class);

// The value is "Hello world"
otherBean2.getValue();

About Performance

Cglib is widely recognized as the best performing library for Bean copying. The majority of its time is spent on creating BeanCopier objects. Therefore, Hutool caches BeanCopier objects based on the passed Class to optimize performance.