How do I copy an object in Java?

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

    Add Cloneable and below code to your class

    public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    

    Use this clonedObject = (YourClass) yourClassObject.clone();

    0 讨论(0)
  • 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;
    }
    }
    
    0 讨论(0)
  • 2020-11-21 05:19

    Here's a decent explanation of clone() if you end up needing it...

    Here: clone (Java method)

    0 讨论(0)
  • 2020-11-21 05:19

    Use a deep cloning utility:

    SomeObjectType copy = new Cloner().deepClone(someObject);
    

    This will deep copy any java object, check it out at https://github.com/kostaskougios/cloning

    0 讨论(0)
  • 2020-11-21 05:22

    Why is there no answer for using Reflection API?

    private static Object cloneObject(Object obj){
            try{
                Object clone = obj.getClass().newInstance();
                for (Field field : obj.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    field.set(clone, field.get(obj));
                }
                return clone;
            }catch(Exception e){
                return null;
            }
        }
    

    It's really simple.

    EDIT: Include child object via recursion

    private static Object cloneObject(Object obj){
            try{
                Object clone = obj.getClass().newInstance();
                for (Field field : obj.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    if(field.get(obj) == null || Modifier.isFinal(field.getModifiers())){
                        continue;
                    }
                    if(field.getType().isPrimitive() || field.getType().equals(String.class)
                            || field.getType().getSuperclass().equals(Number.class)
                            || field.getType().equals(Boolean.class)){
                        field.set(clone, field.get(obj));
                    }else{
                        Object childObj = field.get(obj);
                        if(childObj == obj){
                            field.set(clone, clone);
                        }else{
                            field.set(clone, cloneObject(field.get(obj)));
                        }
                    }
                }
                return clone;
            }catch(Exception e){
                return null;
            }
        }
    
    0 讨论(0)
  • 2020-11-21 05:23

    Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable.

    Check out this wiki article about copying objects.

    Refer here: Object copying

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