原创

java 深拷贝

温馨提示:
本文最后更新于 2025年05月07日,已超过 401 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
  1. 拷贝的类实现序列化
    implements Serializable
  2. 添加序列化id
      private static final long serialVersionUID = 6957528274628957691L;
  3. 使用拷贝方法
           Car car2 = SerialiazableUtil.deepCloneObject(car);
  4. 使用的方法
    import java.io.*;
    
    public class SerialiazableUtil {
    
        public SerialiazableUtil() {
            throw new AssertionError();
        }
    
        @SuppressWarnings("unchecked")
        public static <T extends Serializable> 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;
        }
    }
    
  5. 示例
    
    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);
        }
    }
    
正文到此结束