How do I copy an object in Java?

后端 未结 23 2674
终归单人心
终归单人心 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:19

    I use Google's JSON library to serialize it then create a new instance of the serialized object. It does deep copy with a few restrictions:

    • there can't be any recursive references

    • it won't copy arrays of disparate types

    • arrays and lists should be typed or it won't find the class to instantiate

    • you may need to encapsulate strings in a class you declare yourself

    I also use this class to save user preferences, windows and whatnot to be reloaded at runtime. It is very easy to use and effective.

    import com.google.gson.*;
    
    public class SerialUtils {
    
    //___________________________________________________________________________________
    
    public static String serializeObject(Object o) {
        Gson gson = new Gson();
        String serializedObject = gson.toJson(o);
        return serializedObject;
    }
    //___________________________________________________________________________________
    
    public static Object unserializeObject(String s, Object o){
        Gson gson = new Gson();
        Object object = gson.fromJson(s, o.getClass());
        return object;
    }
           //___________________________________________________________________________________
    public static Object cloneObject(Object o){
        String s = serializeObject(o);
        Object object = unserializeObject(s,o);
        return object;
    }
    }
    

提交回复
热议问题