How do I copy an object in Java?

后端 未结 23 2659
终归单人心
终归单人心 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: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;
            }
        }
    

提交回复
热议问题