Creating an object without going through the constructor

In the following cases, the constructor is not used and the object is created ・ When cloning ・ When deserializing

Run this program and make sure the "Constructor" is only displayed once

Tips0013.java


package jp.avaj.lib.algo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import jp.avaj.lib.test.L;

class Tips0013 {
  public static void main(String[] args) throws CloneNotSupportedException, FileNotFoundException, IOException, ClassNotFoundException {
    //
    Data data = new Data();
    //
    L.p("Execute clone");
    Data copyData = (Data)data.clone();
    //
    L.p("Run Serialize");
    String filename = "./Tips0013.txt";
    ObjectOutputStream oos = null;
    try {
      oos = new ObjectOutputStream(new FileOutputStream(filename));
      oos.writeObject(data);
    }
    finally {
      oos.close();
    }
    L.p("Run deserialize");
    ObjectInputStream ois = null;
    try {
      ois = new ObjectInputStream(new FileInputStream(filename));
      Data newData = (Data)ois.readObject();
    }
    finally {
      ois.close();
    }
    //Delete the work file
    File workFile = new File(filename);
    workFile.delete();
    L.p("Processing Exit");
  }

  private static class Data implements Cloneable,Serializable {
    private String v;
    public Data() {
      v = "aaaa";
      L.p("constructor");
    }
    public Object clone() throws CloneNotSupportedException {
      return super.clone();
    }
  }
}

The result is as follows.

tips0014.txt


constructor
Execute clone
Run Serialize
Run deserialize
Processing Exit

Recommended Posts

Creating an object without going through the constructor
Is there an instance even if the constructor fails?
Talk about going through the source path when delombok