How do you make a deep copy of an object?

前端 未结 19 1873
执念已碎
执念已碎 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: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();
    

提交回复
热议问题