Home > Software engineering >  How to implement a generic deep copy function for an object in Java
How to implement a generic deep copy function for an object in Java

Time:01-12

I'm trying to create a deep copy function for an object in Java, but I want it to be generic so that it can work for any object, not just a specific class. My current implementation uses serialization to create the deep copy, but it feels hacky and inelegant:

public static <T> T deepCopy(T object) {
    
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (T) ois.readObject();
}

Is there a more straightforward way to implement a deep copy function in Java that is both efficient and flexible?

CodePudding user response:

No, there is not. Deep serialization is as good and general as it gets.

(Ideally, code designed using good immutability practices shouldn't need shallow or deep copies.)

  • Related