目标:Java 对象的深拷贝(或克隆)
建议的方法之一(几乎无处不在)是使用 Jackson:
MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.readValue(mapper.writeValueAsString(myPojo), MyPojo.class);
问题:下面的更好吗?在性能方面?有什么缺点吗?
MyPojo myPojo = new MyPojo();
ObjectMapper mapper = new ObjectMapper();
MyPojo newPojo = mapper.treeToValue(mapper.valueToTree(myPojo), MyPojo.class);
最佳答案
Tatu Saloranta 回答:
Second way should be bit more efficient since it only creates and uses logical token stream but does not have to encode JSON and then decode (parse) it to/from token stream. So that is close to optimal regarding Jackson.
About the only thing to make it even more optimal would be to directly use
TokenBuffer
(which is what Jackson itself uses for buffering). Something like:TokenBuffer tb = new TokenBuffer(); // or one of factory methods mapper.writeValue(tb, myPojo); MyPojo copy = mapper.readValue(tb.asParser(), MyPojo.class);
This would further eliminate construction and traversal of the tree model. I don't know how big a difference it'll make, but is not much more code.
谢谢大图:)
关于java - 使用 Jackson : String or JsonNode 进行深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49903859/