Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Member-only story

Java programming, Copy Java object.

--

Press enter or click to view image in full size

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.

  1. 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…

--

--

Nithidol Vacharotayan
Nithidol Vacharotayan

Written by Nithidol Vacharotayan

I write about production failures in Java backend systems: Spring Boot, Kafka, Redis, PostgreSQL, and the trade-offs that only show up after launch.

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development