A
A
Alexander2015-04-28 08:06:22
Java
Alexander, 2015-04-28 08:06:22

How to clone an object in Java?

Found this solution: stackoverflow.com/questions/869033/how-do-i-copy-a...
It didn't work. I don't know how and why, but all the variables in the new object become references to the variables of the old one. Those. in the right place, I created a copy of the object:

MyObject oldObject = new MyObject();
oldObject.someField = 1;
MyObject newObject = new MyObject(oldObject);
oldObject.someField = 2;

and the someField variable of the newObject object also began to equal 2. I tried to write a mega-crutch: in the class that needs to be copied, I created the clone () function and assigned values ​​from the existing object to all variables in it:

public Pot clone() {
        Pot newPot = new Pot();

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field declaredField : fields) {
            try {
                if (declaredField.get(this) == null) {
                    newPot.setValue(declaredField.getName(), null);
                } else {
                    newPot.setValue(declaredField.getName(), declaredField.get(this));
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(PotType.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return newPot;
    }

    public boolean setValue(String key, Object value) {
        try {
            if (!key.equals("initP")) {
                Field declaredField = this.getClass().getField(key);
                declaredField.set(this, value);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            Logger.getLogger(PotType.class.getName()).log(Level.SEVERE, null, ex);

            return false;
        } catch (NoSuchFieldException | SecurityException ex) {
            Logger.getLogger(PotType.class.getName()).log(Level.SEVERE, null, ex);

            return false;
        }
        return true;
    }

MyObject oldObject = new MyObject();
oldObject.someField = 1;
MyObject newObject = oldObject.clone();
oldObject.someField = 2;

And again everything is the same! someField in the new object became equal to two. What the hell is this? :) Please help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DR_Demons, 2015-04-28
@DR_Demons

Java uses the Cloneable interface to clone objects, doesn't it suit you?

example
package my.cloneable;

class User implements Cloneable {
       private String name;
       private int age;
      
       public String getName() {
             return name;
       }
       public void setName(String name) {
             this.name = name;
       }
       public int getAge() {
             return age;
       }
       public void setAge(int age) {
             this.age = age;
       }
      
       public User clone() throws CloneNotSupportedException {
             return (User)super.clone();
       }
}

public class App {

       public static void main(String[] args) {
            
             User user = new User();
            
             user.setName("Иванов");
             user.setAge(25);
            
             System.out.println("Данные до клонирования: " +
user.getName() + " - " + user.getAge() + "лет");
            
             User clone;
             try {
                    clone = user.clone();
                    clone.setName("Петров");
                    clone.setAge(30);
                    System.out.println("Клон после изменения данные: " +
                           clone.getName() + " - " + clone.getAge() + "лет");
                   
             } catch (CloneNotSupportedException e) {
                    System.out.println("Объект не может быть клонированным.");
             }
            
            
             System.out.println("Оригинал, после манипуляций с клоном: " +
 user.getName() + " - " + user.getAge() + "лет");
       }
}
/* результат:
Данные до клонирования: Иванов - 25лет
Клон после изменения данные: Петров - 30лет
Оригинал, после манипуляций с клоном: Иванов - 25лет
 */

V
Vladimir Smirnov, 2015-04-29
@bobzer

You have 2 options:

  1. Use any library for deep cloning . Plus in much less thoughtless coding. The downside is a drop in performance and increased resource consumption. If the number of clone operations in an application is less than a hundred per second, then you don't have to worry about performance.
  2. Write all the cloning yourself, field by field. Plus in high performance - no universal library can be compared in speed with this approach. Minus in the mass of shit code, which also needs to be maintained (with any change in the class, do not forget to refine the clone() methods)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question