How do you make a deep copy of an object?

前端 未结 19 1871
执念已碎
执念已碎 2020-11-21 23:09

It\'s a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

相关标签:
19条回答
  • 2020-11-21 23:43

    For Spring Framework users. Using class org.springframework.util.SerializationUtils:

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T object) {
         return (T) SerializationUtils.deserialize(SerializationUtils.serialize(object));
    }
    
    0 讨论(0)
  • 2020-11-21 23:43

    Using Jackson to serialize and deserialize the object. This implementation does not require the object to implement the Serializable class.

      <T> T clone(T object, Class<T> clazzType) throws IOException {
    
        final ObjectMapper objMapper = new ObjectMapper();
        String jsonStr= objMapper.writeValueAsString(object);
    
        return objMapper.readValue(jsonStr, clazzType);
    
      }
    
    0 讨论(0)
  • 2020-11-21 23:45

    1)

    public static Object deepClone(Object object) {
       try {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(object);
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
         ObjectInputStream ois = new ObjectInputStream(bais);
         return ois.readObject();
       }
       catch (Exception e) {
         e.printStackTrace();
         return null;
       }
     }
    
    2)
    
        // (1) create a MyPerson object named Al
        MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");
        MyPerson al = new MyPerson("Al", "Arun", address);
    
        // (2) make a deep clone of Al
        MyPerson neighbor = (MyPerson)deepClone(al);
    

    Here your MyPerson and MyAddress class must implement serilazable interface

    0 讨论(0)
  • 2020-11-21 23:48

    BeanUtils does a really good job deep cloning beans.

    BeanUtils.cloneBean(obj);
    
    0 讨论(0)
  • 2020-11-21 23:51

    One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.

    From https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator :

    JsonFactory f = mapper.getFactory(); // may alternatively construct directly too
    
    // First: write simple JSON output
    File jsonFile = new File("test.json");
    JsonGenerator g = f.createGenerator(jsonFile);
    // write JSON: { "message" : "Hello world!" }
    g.writeStartObject();
    g.writeStringField("message", "Hello world!");
    g.writeEndObject();
    g.close();
    
    // Second: read file back
    JsonParser p = f.createParser(jsonFile);
    
    JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
    t = p.nextToken(); // JsonToken.FIELD_NAME
    if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
       // handle error
    }
    t = p.nextToken();
    if (t != JsonToken.VALUE_STRING) {
       // similarly
    }
    String msg = p.getText();
    System.out.printf("My message to you is: %s!\n", msg);
    p.close();
    
    0 讨论(0)
  • 2020-11-21 23:51

    Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

    0 讨论(0)
提交回复
热议问题