Answer the question
In order to leave comments, you need to log in
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;
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;
Answer the question
In order to leave comments, you need to log in
Java uses the Cloneable interface to clone objects, doesn't it suit you?
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лет
*/
You have 2 options:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question