Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy properties from one Java bean to another?

Tags:

java

javabeans

I have a simple Java POJO that I would copy properties to another instance of same POJO class.

I know I can do that with BeanUtils.copyProperties() but I would like to avoid use of a third-party library.

So, how to do that simply, the proper and safer way ?

By the way, I'm using Java 6.

like image 733
paulgreg Avatar asked May 07 '09 15:05

paulgreg


People also ask

How do you copy properties of beans?

Copy Bean Properties Copying properties of one object to another object is often tedious and error-prone for developers. BeanUtils class provides a copyProperties method that copies the properties of source object to target object where the property name is same in both objects.


1 Answers

I guess if you look at the source code of BeanUtils, it will show you how to do this without actually using BeanUtils.

If you simply want to create a copy of a POJO (not quite the same thing as copying the properties from one POJO to another), you could change the source bean to implement the clone() method and the Cloneable interface.

like image 200
Dónal Avatar answered Sep 20 '22 15:09

Dónal