How do I copy an object in Java?

后端 未结 23 2716
终归单人心
终归单人心 2020-11-21 04:50

Consider the code below:

DummyBean dum = new DummyBean();
dum.setDummy(\"foo\");
System.out.println(dum.getDummy()); // prints \'foo\'

DummyBean dumtwo = du         


        
23条回答
  •  春和景丽
    2020-11-21 05:11

    Use gson for duplicating an object.

    public static T copyObject(Object object){
        Gson gson = new Gson();
        JsonObject jsonObject = gson.toJsonTree(object).getAsJsonObject();
        return gson.fromJson(jsonObject,(Type) object.getClass());
    }
    

    Assume I have an object person.So

    Person copyPerson = copyObject(person);
    

    Note: The performance is much slower.

提交回复
热议问题