Member-only story
Java programming, Copy Java object.
A developer who wants to copy an object usually faces problems when changing the original object's value. Then, the clone object's value has been changing, too, because, in Java programming, the objects reference each other. To prevent this problem, the developer should copy objects using several methods, such as Serialization.
Not a Medium member? No problem! Read the full article here. Enjoy!
For example, copy an object.
- The developer copies objects using Cloneable.
Create Java bean with implements Cloneable.
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PersonClone implements Cloneable {
private String name;
private int age;
public PersonClone(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}Create a Java class to copy the Java object bean using the clone method.
import com.example.beans.PersonClone;
public class CopyObjectClone {
public static void main(String[] args) {
try {
PersonClone…










