java 深拷贝
温馨提示:
本文最后更新于 2025年05月07日,已超过 401 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
- 拷贝的类实现序列化
implements Serializable - 添加序列化id
private static final long serialVersionUID = 6957528274628957691L; - 使用拷贝方法
Car car2 = SerialiazableUtil.deepCloneObject(car); - 使用的方法
import java.io.*; public class SerialiazableUtil { public SerialiazableUtil() { throw new AssertionError(); } @SuppressWarnings("unchecked") public static T deepCloneObject(Object object) throws IOException { T deepClone = null; ObjectInputStream ois = null; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); ) { oos.writeObject(object); ByteArrayInputStream bais = new ByteArrayInputStream(baos .toByteArray()); ois = new ObjectInputStream(bais); deepClone = (T) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { if (ois != null) { ois.close(); } } return deepClone; } } - 示例
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.beans.BeanUtils; import java.io.IOException; import java.io.Serializable; @AllArgsConstructor @Data @NoArgsConstructor public class Car implements Serializable { private static final long serialVersionUID = 6957528274628957691L; private String brand;//品牌 private int maxSpeed;//最高时速 public static void main(String[] args) throws IOException { Car car = new Car("bc", 133); Car car1 = new Car(); //浅拷贝 BeanUtils.copyProperties(car, car1); // 深拷贝 Car car2 = SerialiazableUtil.deepCloneObject(car); System.out.print("Java默认序列化方式:"); // System.out.println(person.getCar()==person1.getCar()); System.out.println(car); System.out.println("========================="); System.out.println(car1); System.out.println("========================="); System.out.println(car.brand == car2.brand); } }
正文到此结束
- 本文标签: Java
- 本文链接: http://119.91.109.247:8443//article/59
- 版权声明: 本文由张亚东原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权