views:

4060

answers:

3

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.

+5  A: 

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.

Don
If all of the properties are backed by fields, making it cloneable should do nicely, and is very efficient. However, note that it's a shallow copy...
Scott Stanchfield
It's a shallow copy if you merely implement Cloneable and overrid clone() to make it public and call the parent implementation. But of course, you could implement clone() to do anything, including creating a deep copy. Check out 'Effective Java' for further details about clone().
Don
+1  A: 

Have a look at the JavaBeans API, in particular the Introspector class. You can use the BeanInfo metadata to get and set properties. It is a good idea to read up on the JavaBeans specification if you haven't already. It also helps to have a passing familiarity with the reflection API.

McDowell
Good advice, but it's probably fair to assume the end result of all that will probably be an inferior implementation of BeanUtils.copyProperties()
Don
That's a fair comment, but it never hurts to know what's going on.
McDowell
Thx. I'm new with Java 6 so I hoped there will be a way to do that more easily than on previous versions. But I will definitely take a look on your links.
paulgreg
+1  A: 

There is no simple way to do it. Introspector and the Java beans libraries are monolithic - BeanUtils is a simple wrapper around this and works well. Not having libraries just to not have libraries is a bad idea in general - there's a reason it's commons to begin with - common functionality that should exist with Java, but doesn't.

MetroidFan2002