Если ваши объекты реализуют Serializable, вы можете использовать writeObject () и readObject () для создания глубокой копии. У нас есть иерархия объектов передачи данных и мы поддерживаем глубокие копии с помощью этого метода в абстрактном суперклассе (DTO):
/**
* Reply a deep copy of this DTO. This generic method works for any DTO subclass:
*
* Person person = new Person();
* Person copy = person.deepCopy();
*
* Note: Using Java serialization is easy, but can be expensive. Use with care.
*
* @return A deep copy of this DTO.
*/
@SuppressWarnings("unchecked")
public <T extends DTO> T deepCopy()
{
try
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
oos.flush();
ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
return (T) ois.readObject();
}
finally
{
oos.close();
ois.close();
}
}
catch ( ClassNotFoundException cnfe )
{
// Impossible, since both sides deal in the same loaded classes.
return null;
}
catch ( IOException ioe )
{
// This has to be "impossible", given that oos and ois wrap a *byte array*.
return null;
}
}
(Я уверен, что кто-то найдет причину, по которой эти исключения могут возникнуть.)
Другие библиотеки сериализации (например, XStream) могут использоваться таким же образом.